From e7ff1eec811502af7f9d6f85c16b8c9d64b075e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Thu, 19 Feb 2026 11:38:56 -0300 Subject: [PATCH] add WebRTC tests --- tests/integration/test_webrtc_bridge.zig | 270 ++++++ tests/integration/test_webrtc_cleanup.zig | 235 ++++++ tests/integration/test_webrtc_e2e.zig | 338 ++++++++ tests/integration/test_webrtc_loopback.zig | 176 ++++ tests/integration/test_webrtc_multi_peer.zig | 469 +++++++++++ tests/integration/test_webrtc_noise.zig | 234 ++++++ .../test_webrtc_p2p_integration.zig | 192 +++++ tests/integration/test_webrtc_smoke.zig | 74 ++ tests/integration/test_webrtc_transfer.zig | 776 ++++++++++++++++++ 9 files changed, 2764 insertions(+) create mode 100644 tests/integration/test_webrtc_bridge.zig create mode 100644 tests/integration/test_webrtc_cleanup.zig create mode 100644 tests/integration/test_webrtc_e2e.zig create mode 100644 tests/integration/test_webrtc_loopback.zig create mode 100644 tests/integration/test_webrtc_multi_peer.zig create mode 100644 tests/integration/test_webrtc_noise.zig create mode 100644 tests/integration/test_webrtc_p2p_integration.zig create mode 100644 tests/integration/test_webrtc_smoke.zig create mode 100644 tests/integration/test_webrtc_transfer.zig diff --git a/tests/integration/test_webrtc_bridge.zig b/tests/integration/test_webrtc_bridge.zig new file mode 100644 index 0000000..ab67d42 --- /dev/null +++ b/tests/integration/test_webrtc_bridge.zig @@ -0,0 +1,270 @@ +//! Integration tests for the WebRTC Bridge. +//! +//! Tests the bridge's signaling message parsing, JSON helpers, bridge +//! lifecycle, queue overflow protection, and reconnection state. + +const std = @import("std"); +const testing = std.testing; +const webrtc_bridge = @import("webrtc_bridge"); + +const WebRTCBridge = webrtc_bridge.WebRTCBridge; +const BridgeChannelTransport = webrtc_bridge.BridgeChannelTransport; + +// ============================================================================ +// JSON parsing tests (exercise the signaling message parser) +// ============================================================================ + +test "parseSignalingMessage: offer" { + const data = + \\{"type":"offer","from":"alice","sdp":"v=0..."} + ; + const msg = webrtc_bridge.parseSignalingMessage(data) orelse { + return error.ParseFailed; + }; + try testing.expectEqual(.offer, msg.msg_type); + try testing.expectEqualStrings("alice", msg.from.?); + try testing.expectEqualStrings("v=0...", msg.sdp.?); +} + +test "parseSignalingMessage: answer" { + const data = + \\{"type":"answer","from":"bob","sdp":"v=0a=..."} + ; + const msg = webrtc_bridge.parseSignalingMessage(data) orelse { + return error.ParseFailed; + }; + try testing.expectEqual(.answer, msg.msg_type); + try testing.expectEqualStrings("bob", msg.from.?); +} + +test "parseSignalingMessage: candidate" { + const data = + \\{"type":"candidate","from":"alice","candidate":"candidate:1 ...","sdpMid":"0"} + ; + const msg = webrtc_bridge.parseSignalingMessage(data) orelse { + return error.ParseFailed; + }; + try testing.expectEqual(.candidate, msg.msg_type); + try testing.expectEqualStrings("alice", msg.from.?); + try testing.expectEqualStrings("candidate:1 ...", msg.candidate.?); + try testing.expectEqualStrings("0", msg.sdp_mid.?); +} + +test "parseSignalingMessage: registered" { + const data = + \\{"type":"registered","peerId":"myid"} + ; + const msg = webrtc_bridge.parseSignalingMessage(data) orelse { + return error.ParseFailed; + }; + try testing.expectEqual(.registered, msg.msg_type); + try testing.expectEqualStrings("myid", msg.peer_id.?); +} + +test "parseSignalingMessage: error" { + const data = + \\{"type":"error","message":"peer not found"} + ; + const msg = webrtc_bridge.parseSignalingMessage(data) orelse { + return error.ParseFailed; + }; + try testing.expectEqual(.@"error", msg.msg_type); + try testing.expectEqualStrings("peer not found", msg.message.?); +} + +test "parseSignalingMessage: invalid JSON returns null" { + try testing.expect(webrtc_bridge.parseSignalingMessage("not json") == null); + try testing.expect(webrtc_bridge.parseSignalingMessage("{}") == null); + try testing.expect(webrtc_bridge.parseSignalingMessage("") == null); +} + +test "jsonGetString: basic extraction" { + const json = + \\{"name":"value","other":"data"} + ; + const val = webrtc_bridge.jsonGetString(json, "name"); + try testing.expect(val != null); + try testing.expectEqualStrings("value", val.?); + + const other = webrtc_bridge.jsonGetString(json, "other"); + try testing.expect(other != null); + try testing.expectEqualStrings("data", other.?); +} + +test "jsonGetString: missing key returns null" { + const json = + \\{"name":"value"} + ; + try testing.expect(webrtc_bridge.jsonGetString(json, "missing") == null); +} + +// ============================================================================ +// Bridge lifecycle tests +// ============================================================================ + +test "WebRTCBridge: init and deinit without connect" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + try testing.expect(!bridge.connected); + try testing.expectEqual(@as(@TypeOf(bridge.ws_id), -1), bridge.ws_id); +} + +test "WebRTCBridge: connect fails without WebRTC library" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + // WebRTC library is not loaded in test env, so connect should fail + const result = bridge.connect(); + try testing.expectError(error.WebRTCNotAvailable, result); +} + +test "WebRTCBridge: update is safe when not connected" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + // Should not crash + bridge.update(); + bridge.update(); + bridge.update(); +} + +test "WebRTCBridge: disconnect is safe when not connected" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + // Should not crash + bridge.disconnect(); + bridge.disconnect(); +} + +// ============================================================================ +// Queue overflow tests (BridgeChannelTransport) +// ============================================================================ + +test "BridgeChannelTransport: pushMessage stays bounded at MAX_RECV_QUEUE" { + var bct = BridgeChannelTransport.init(testing.allocator, 42); + defer bct.deinit(); + + // Push more than MAX_RECV_QUEUE messages + const max_queue = 8192; + const overflow = 100; + for (0..max_queue + overflow) |i| { + var buf: [8]u8 = undefined; + std.mem.writeInt(u64, &buf, @intCast(i), .little); + bct.pushMessage(&buf); + } + + // Queue should be capped at MAX_RECV_QUEUE + bct.mutex.lock(); + defer bct.mutex.unlock(); + try testing.expectEqual(@as(usize, max_queue), bct.recv_queue.items.len); + + // First message should be the one after overflow drops (oldest dropped) + const first = bct.recv_queue.items[0]; + const first_val = std.mem.readInt(u64, first[0..8], .little); + try testing.expectEqual(@as(u64, overflow), first_val); +} + +test "BridgeChannelTransport: FIFO order preserved after overflow" { + var bct = BridgeChannelTransport.init(testing.allocator, 42); + defer bct.deinit(); + + // Push a small number of messages and verify order + for (0..10) |i| { + var buf: [4]u8 = undefined; + std.mem.writeInt(u32, &buf, @intCast(i), .little); + bct.pushMessage(&buf); + } + + // Drain and verify order + for (0..10) |i| { + bct.mutex.lock(); + const msg = bct.recv_queue.orderedRemove(0); + bct.mutex.unlock(); + defer testing.allocator.free(msg); + const val = std.mem.readInt(u32, msg[0..4], .little); + try testing.expectEqual(@as(u32, @intCast(i)), val); + } +} + +// ============================================================================ +// Reconnection state tests +// ============================================================================ + +test "WebRTCBridge: auto_reconnect defaults to true" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + try testing.expect(bridge.auto_reconnect); + try testing.expectEqual(@as(u32, 1000), bridge.reconnect_delay_ms); + try testing.expectEqual(@as(u32, 30_000), bridge.reconnect_max_delay_ms); +} + +test "WebRTCBridge: auto_reconnect can be disabled" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + bridge.auto_reconnect = false; + try testing.expect(!bridge.auto_reconnect); + + // Update should be safe with auto_reconnect disabled + bridge.update(); +} + +test "WebRTCBridge: pollDirectMessage returns null when empty" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + try testing.expect(bridge.pollDirectMessage() == null); +} + +test "WebRTCBridge: pollNewPeer returns null when empty" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + try testing.expect(bridge.pollNewPeer() == null); +} + +test "WebRTCBridge: getFirstDcId returns null when no channels" { + var bridge = WebRTCBridge.init( + testing.allocator, + "ws://localhost:9999", + "test-peer", + ); + defer bridge.deinit(); + + try testing.expect(bridge.getFirstDcId() == null); +} diff --git a/tests/integration/test_webrtc_cleanup.zig b/tests/integration/test_webrtc_cleanup.zig new file mode 100644 index 0000000..17d019d --- /dev/null +++ b/tests/integration/test_webrtc_cleanup.zig @@ -0,0 +1,235 @@ +//! WebRTC Cleanup and Resource Management Tests +//! +//! Verifies: +//! 1. Proper cleanup: close DataChannels, delete PeerConnections +//! 2. Edge case: destroy channel before DataChannel opens +//! 3. Edge case: destroy during ICE gathering +//! 4. Leak test: multiple connections created+closed, zero leaked allocations +//! +//! Requires: libdatachannel.dylib available + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; +const core = @import("core"); + +/// Wait for a condition with timeout (milliseconds). +fn waitFor(comptime predicate: anytype, ctx: anytype, timeout_ms: u64) bool { + var waited: u64 = 0; + const poll_ms: u64 = 10; + while (waited < timeout_ms) : (waited += poll_ms) { + if (predicate(ctx)) return true; + std.Thread.sleep(poll_ms * std.time.ns_per_ms); + } + return false; +} + +test "WebRTC cleanup: destroy channel immediately after create" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Create and immediately destroy — should not leak + const cs = try mgr.createOffer(null); + mgr.destroyChannel(cs); +} + +test "WebRTC cleanup: destroy before gathering completes" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + const cs = try mgr.createOffer(null); + + // Wait just for SDP but NOT for gathering to complete + _ = waitFor(struct { + fn check(ch: *webrtc.ChannelState) bool { + return ch.getLocalSdp() != null; + } + }.check, cs, 3000); + + // Destroy mid-gathering — should not crash or leak + mgr.destroyChannel(cs); +} + +test "WebRTC cleanup: full connection lifecycle 10x" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Run 10 full connection lifecycles + var i: usize = 0; + while (i < 10) : (i += 1) { + const alice = try mgr.createOffer(null); + errdefer mgr.destroyChannel(alice); + + // Wait for SDP + gathering + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, alice, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, alice, 5000)); + + const alice_sdp_z = try allocator.dupeZ(u8, alice.getLocalSdp().?); + defer allocator.free(alice_sdp_z); + + const bob = try mgr.acceptOffer(alice_sdp_z, null); + errdefer mgr.destroyChannel(bob); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, bob, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, bob, 5000)); + + // Exchange SDP + const bob_sdp_z = try allocator.dupeZ(u8, bob.getLocalSdp().?); + defer allocator.free(bob_sdp_z); + try testing.expect(rtc.rtcSetRemoteDescription(alice.pc_id, bob_sdp_z, "answer") >= 0); + + // Exchange ICE candidates + { + const cands = try bob.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(alice, z); + } + } + { + const cands = try alice.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(bob, z); + } + } + + // Wait for DataChannel open + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, alice, 10000)); + + // Send a message + _ = try mgr.send(alice, "iteration"); + + // Wait for receipt + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, bob, 5000)); + + // Verify + const msg = bob.popRecvMessage().?; + defer allocator.free(msg.data); + try testing.expectEqualStrings("iteration", msg.data); + + // Destroy both peers + mgr.destroyChannel(bob); + mgr.destroyChannel(alice); + } + // If we get here without test allocator detecting leaks, cleanup is correct +} + +test "WebRTC cleanup: ChannelState with queued messages" { + const allocator = testing.allocator; + + // Create ChannelState directly and push messages, then verify cleanup + var cs = webrtc.ChannelState.init(allocator, -1); + + // Push some messages + cs.pushRecvMessage("hello"); + cs.pushRecvMessage("world"); + + // Set SDP + cs.setLocalSdp("v=0\r\n", "offer"); + + // Add candidates + cs.addLocalCandidate("candidate:1 1 UDP 1 127.0.0.1 12345 typ host"); + + // Verify state + try testing.expect(cs.getLocalSdp() != null); + { + cs.mutex.lock(); + defer cs.mutex.unlock(); + try testing.expectEqual(@as(usize, 2), cs.recv_queue.items.len); + try testing.expectEqual(@as(usize, 1), cs.local_candidates.items.len); + } + + // Deinit should free everything without leaks + cs.deinit(); +} + +test "WebRTC cleanup: PeerConnection with WebRTC transport" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + + const network = @import("network"); + const PeerConnection = network.PeerConnection; + const Transport = core.transport.Transport; + + // Create a mock-like setup: ChannelState + WebRTCChannelTransport + PeerConnection + // We can't use a real WebRTC connection here because we need the manager alive, + // but we can verify PeerConnection.initWithTransport + deinit works cleanly. + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + const cs = try mgr.createOffer(null); + defer mgr.destroyChannel(cs); + + var wrtc_transport = webrtc.WebRTCChannelTransport.init(&mgr, cs); + const transport = Transport.init(&wrtc_transport); + + const pc = try PeerConnection.initWithTransport(allocator, transport); + try testing.expect(pc.socket == null); + + // Deinit PeerConnection — should not try to close a null socket + pc.deinit(); +} diff --git a/tests/integration/test_webrtc_e2e.zig b/tests/integration/test_webrtc_e2e.zig new file mode 100644 index 0000000..2978e4c --- /dev/null +++ b/tests/integration/test_webrtc_e2e.zig @@ -0,0 +1,338 @@ +//! WebRTC End-to-End Integration Test — Phase 5 comprehensive test +//! +//! Validates the full WebRTC stack working together: +//! 1. DHT-based signaling: SDP exchange via SignalingSession +//! 2. Trickle ICE via versioned DHT keys +//! 3. WebRTC DataChannel establishment +//! 4. Noise XX handshake over DataChannel +//! 5. Encrypted bidirectional messaging +//! 6. Wire envelope key derivation +//! 7. Transport vtable integration with PeerConnection +//! 8. Cleanup and resource management +//! +//! Requires: libdatachannel.dylib available + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; +const core = @import("core"); +const network = @import("network"); +const noise = @import("noise"); +const Transport = core.transport.Transport; +const SecureConnection = network.SecureConnection; +const SecureError = network.secure_connection.Error; +const PeerConnection = network.PeerConnection; + +/// Wait for a condition with timeout (milliseconds). +fn waitFor(comptime predicate: anytype, ctx: anytype, timeout_ms: u64) bool { + var waited: u64 = 0; + const poll_ms: u64 = 10; + while (waited < timeout_ms) : (waited += poll_ms) { + if (predicate(ctx)) return true; + std.Thread.sleep(poll_ms * std.time.ns_per_ms); + } + return false; +} + +/// Establish a WebRTC DataChannel pair using direct SDP exchange. +fn setupWebRTCPair(allocator: std.mem.Allocator, mgr: *webrtc.NativeWebRTCManager) !struct { alice: *webrtc.ChannelState, bob: *webrtc.ChannelState } { + const alice = try mgr.createOffer(null); + errdefer mgr.destroyChannel(alice); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, alice, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, alice, 5000)); + + const alice_sdp_z = try allocator.dupeZ(u8, alice.getLocalSdp().?); + defer allocator.free(alice_sdp_z); + + const bob = try mgr.acceptOffer(alice_sdp_z, null); + errdefer mgr.destroyChannel(bob); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, bob, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, bob, 5000)); + + const bob_sdp_z = try allocator.dupeZ(u8, bob.getLocalSdp().?); + defer allocator.free(bob_sdp_z); + try testing.expect(rtc.rtcSetRemoteDescription(alice.pc_id, bob_sdp_z, "answer") >= 0); + + // Exchange ICE candidates + { + const cands = try bob.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(alice, z); + } + } + { + const cands = try alice.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(bob, z); + } + } + + // Wait for DataChannels to open + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, alice, 10000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, bob, 10000)); + + return .{ .alice = alice, .bob = bob }; +} + +test "E2E: WebRTC + Noise + PeerConnection full stack" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Step 1: Establish WebRTC DataChannel pair + const pair = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(pair.alice); + defer mgr.destroyChannel(pair.bob); + + // Step 2: Wrap in Transport vtable + var alice_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, pair.alice); + var bob_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, pair.bob); + + const alice_transport = Transport.init(&alice_wrtc); + const bob_transport = Transport.init(&bob_wrtc); + + // Step 3: Create PeerConnections with WebRTC transport (no socket) + const alice_pc = try PeerConnection.initWithTransport(allocator, alice_transport); + defer alice_pc.deinit(); + const bob_pc = try PeerConnection.initWithTransport(allocator, bob_transport); + defer bob_pc.deinit(); + + // Verify no socket (WebRTC path) + try testing.expect(alice_pc.socket == null); + try testing.expect(bob_pc.socket == null); + + // Step 4: Create Noise keypairs and SecureConnections + const alice_kp = noise.KeyPair.generate(); + const bob_kp = noise.KeyPair.generate(); + + const alice_sec = try allocator.create(SecureConnection); + defer allocator.destroy(alice_sec); + alice_sec.initWithTransport(alice_transport, alice_kp, allocator); + + const bob_sec = try allocator.create(SecureConnection); + defer allocator.destroy(bob_sec); + bob_sec.initWithTransport(bob_transport, bob_kp, allocator); + + // Step 5: Run Noise XX handshake on separate threads + const HandshakeCtx = struct { + sec: *SecureConnection, + err: ?SecureError = null, + }; + + var alice_ctx = HandshakeCtx{ .sec = alice_sec }; + var bob_ctx = HandshakeCtx{ .sec = bob_sec }; + + const alice_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.initiateHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&alice_ctx}); + + const bob_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.acceptHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&bob_ctx}); + + alice_thread.join(); + bob_thread.join(); + + if (alice_ctx.err) |err| { + std.log.err("Alice handshake failed: {}", .{err}); + return error.TestUnexpectedResult; + } + if (bob_ctx.err) |err| { + std.log.err("Bob handshake failed: {}", .{err}); + return error.TestUnexpectedResult; + } + + // Step 6: Verify handshake results + try testing.expect(alice_sec.isEncrypted()); + try testing.expect(bob_sec.isEncrypted()); + + // Verify remote public keys + const alice_remote = alice_sec.getRemotePublicKey().?; + const bob_remote = bob_sec.getRemotePublicKey().?; + try testing.expectEqualSlices(u8, &bob_kp.public, &alice_remote); + try testing.expectEqualSlices(u8, &alice_kp.public, &bob_remote); + + // Verify wire envelope keys were derived + try testing.expect(alice_sec.envelope_key != null); + try testing.expect(bob_sec.envelope_key != null); + + // Step 7: Exchange multiple encrypted messages (bidirectional) + const messages = [_][]const u8{ + "Hello from Alice over WebRTC!", + "Message 2: Testing reliability", + "Message 3: End-to-end encryption verified", + }; + + for (messages) |plaintext| { + _ = try alice_sec.send(plaintext); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, pair.bob, 5000)); + + var recv_buf: [1024]u8 = undefined; + const decrypted = try bob_sec.receive(&recv_buf); + try testing.expectEqualStrings(plaintext, decrypted); + } + + // Bob replies + const reply = "All messages received! Reply from Bob."; + _ = try bob_sec.send(reply); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, pair.alice, 5000)); + + var reply_buf: [1024]u8 = undefined; + const reply_decrypted = try alice_sec.receive(&reply_buf); + try testing.expectEqualStrings(reply, reply_decrypted); +} + +test "E2E: WebRTC connection repeated setup/teardown" { + if (!rtc.load()) return error.SkipZigTest; + + // Verify that creating and tearing down multiple WebRTC connections + // with full Noise handshakes doesn't leak resources. + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + var i: usize = 0; + while (i < 3) : (i += 1) { + const pair = try setupWebRTCPair(allocator, &mgr); + + var alice_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, pair.alice); + var bob_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, pair.bob); + + const alice_transport = Transport.init(&alice_wrtc); + const bob_transport = Transport.init(&bob_wrtc); + + const alice_kp = noise.KeyPair.generate(); + const bob_kp = noise.KeyPair.generate(); + + const alice_sec = try allocator.create(SecureConnection); + alice_sec.initWithTransport(alice_transport, alice_kp, allocator); + + const bob_sec = try allocator.create(SecureConnection); + bob_sec.initWithTransport(bob_transport, bob_kp, allocator); + + // Handshake + const HandshakeCtx = struct { + sec: *SecureConnection, + err: ?SecureError = null, + }; + + var alice_ctx = HandshakeCtx{ .sec = alice_sec }; + var bob_ctx = HandshakeCtx{ .sec = bob_sec }; + + const alice_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.initiateHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&alice_ctx}); + + const bob_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.acceptHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&bob_ctx}); + + alice_thread.join(); + bob_thread.join(); + + try testing.expect(alice_ctx.err == null); + try testing.expect(bob_ctx.err == null); + try testing.expect(alice_sec.isEncrypted()); + try testing.expect(bob_sec.isEncrypted()); + + // Quick message exchange + _ = try alice_sec.send("iteration test"); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, pair.bob, 5000)); + + var buf: [1024]u8 = undefined; + const msg = try bob_sec.receive(&buf); + try testing.expectEqualStrings("iteration test", msg); + + // Cleanup + allocator.destroy(alice_sec); + allocator.destroy(bob_sec); + mgr.destroyChannel(pair.bob); + mgr.destroyChannel(pair.alice); + } + // If allocator doesn't report leaks, cleanup is correct +} diff --git a/tests/integration/test_webrtc_loopback.zig b/tests/integration/test_webrtc_loopback.zig new file mode 100644 index 0000000..dd91199 --- /dev/null +++ b/tests/integration/test_webrtc_loopback.zig @@ -0,0 +1,176 @@ +//! WebRTC Loopback Test — two native WebRTC peers exchange data. +//! +//! Flow: +//! 1. Alice creates offer (SDP + ICE candidates) +//! 2. Bob accepts Alice's offer (generates answer SDP + ICE candidates) +//! 3. Alice receives Bob's answer and ICE candidates +//! 4. DataChannels open on both sides +//! 5. Alice sends "hello world", Bob receives it +//! 6. Bob sends "hello back", Alice receives it +//! +//! Requires: libdatachannel.dylib available + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; + +/// Wait for a condition with timeout (milliseconds). +fn waitFor(comptime predicate: anytype, ctx: anytype, timeout_ms: u64) bool { + var waited: u64 = 0; + const poll_ms: u64 = 10; + while (waited < timeout_ms) : (waited += poll_ms) { + if (predicate(ctx)) return true; + std.Thread.sleep(poll_ms * std.time.ns_per_ms); + } + return false; +} + +test "webrtc loopback: two peers exchange messages" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // --- Step 1: Alice creates offer --- + const alice = try mgr.createOffer(null); + defer mgr.destroyChannel(alice); + + // Wait for Alice's SDP to be generated + const got_alice_sdp = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, alice, 5000); + try testing.expect(got_alice_sdp); + + // Wait for Alice's ICE gathering to complete + const alice_gathered = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, alice, 5000); + try testing.expect(alice_gathered); + + // Get Alice's offer SDP (need null-terminated copy) + const alice_sdp_slice = alice.getLocalSdp().?; + const alice_sdp_z = try allocator.dupeZ(u8, alice_sdp_slice); + defer allocator.free(alice_sdp_z); + + // --- Step 2: Bob accepts Alice's offer --- + const bob = try mgr.acceptOffer(alice_sdp_z, null); + defer mgr.destroyChannel(bob); + + // Wait for Bob's answer SDP + const got_bob_sdp = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, bob, 5000); + try testing.expect(got_bob_sdp); + + // Wait for Bob's ICE gathering + const bob_gathered = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, bob, 5000); + try testing.expect(bob_gathered); + + // --- Step 3: Exchange Bob's answer back to Alice --- + const bob_sdp_slice = bob.getLocalSdp().?; + const bob_sdp_z = try allocator.dupeZ(u8, bob_sdp_slice); + defer allocator.free(bob_sdp_z); + + const result = rtc.rtcSetRemoteDescription(alice.pc_id, bob_sdp_z, "answer"); + try testing.expect(result >= 0); + + // Exchange ICE candidates: Bob → Alice + { + const bob_candidates = try bob.drainLocalCandidates(allocator); + defer { + for (bob_candidates) |c| allocator.free(c); + if (bob_candidates.len > 0) allocator.free(bob_candidates); + } + for (bob_candidates) |cand| { + const cand_z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(cand_z); + mgr.addRemoteCandidate(alice, cand_z); + } + } + + // Exchange ICE candidates: Alice → Bob + { + const alice_candidates = try alice.drainLocalCandidates(allocator); + defer { + for (alice_candidates) |c| allocator.free(c); + if (alice_candidates.len > 0) allocator.free(alice_candidates); + } + for (alice_candidates) |cand| { + const cand_z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(cand_z); + mgr.addRemoteCandidate(bob, cand_z); + } + } + + // --- Step 4: Wait for DataChannels to open --- + const alice_open = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, alice, 10000); + try testing.expect(alice_open); + + const bob_open = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, bob, 10000); + try testing.expect(bob_open); + + // --- Step 5: Alice sends to Bob --- + const msg = "hello world"; + const sent = try mgr.send(alice, msg); + try testing.expectEqual(msg.len, sent); + + // Wait for Bob to receive + const bob_received = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, bob, 5000); + try testing.expect(bob_received); + + // Read Bob's received message + const recv_msg = bob.popRecvMessage().?; + defer allocator.free(recv_msg.data); + try testing.expectEqualStrings(msg, recv_msg.data); + + // --- Step 6: Bob sends back to Alice --- + const reply = "hello back"; + const bob_dc = bob.dc_id.load(.acquire); + try testing.expect(bob_dc >= 0); + const reply_result = rtc.rtcSendMessage(bob_dc, reply.ptr, @intCast(reply.len)); + try testing.expect(reply_result >= 0); + + // Wait for Alice to receive + const alice_received = waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, alice, 5000); + try testing.expect(alice_received); + + const alice_recv = alice.popRecvMessage().?; + defer allocator.free(alice_recv.data); + try testing.expectEqualStrings(reply, alice_recv.data); +} diff --git a/tests/integration/test_webrtc_multi_peer.zig b/tests/integration/test_webrtc_multi_peer.zig new file mode 100644 index 0000000..53008bf --- /dev/null +++ b/tests/integration/test_webrtc_multi_peer.zig @@ -0,0 +1,469 @@ +//! WebRTC Multi-Peer Mesh Test — Phase 5 +//! +//! Validates that the WebRTC transport abstraction scales beyond 2 peers: +//! 1. Three-node mesh with raw DataChannel messaging +//! 2. Three-node mesh with Noise encryption on one link +//! 3. 1GB file transfer across mesh with SHA-256 integrity verification +//! +//! Requires: libdatachannel.dylib available + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; +const core = @import("core"); +const network = @import("network"); +const noise = @import("noise"); +const Transport = core.transport.Transport; +const SecureConnection = network.SecureConnection; +const SecureError = network.secure_connection.Error; +const PeerConnection = network.PeerConnection; + +/// Wait for a condition with timeout (milliseconds). +fn waitFor(comptime predicate: anytype, ctx: anytype, timeout_ms: u64) bool { + var waited: u64 = 0; + const poll_ms: u64 = 10; + while (waited < timeout_ms) : (waited += poll_ms) { + if (predicate(ctx)) return true; + std.Thread.sleep(poll_ms * std.time.ns_per_ms); + } + return false; +} + +/// Establish a WebRTC DataChannel pair using direct SDP exchange. +fn setupWebRTCPair(allocator: std.mem.Allocator, mgr: *webrtc.NativeWebRTCManager) !struct { offerer: *webrtc.ChannelState, answerer: *webrtc.ChannelState } { + const offerer = try mgr.createOffer(null); + errdefer mgr.destroyChannel(offerer); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, offerer, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, offerer, 5000)); + + const offerer_sdp_z = try allocator.dupeZ(u8, offerer.getLocalSdp().?); + defer allocator.free(offerer_sdp_z); + + const answerer = try mgr.acceptOffer(offerer_sdp_z, null); + errdefer mgr.destroyChannel(answerer); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, answerer, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, answerer, 5000)); + + const answerer_sdp_z = try allocator.dupeZ(u8, answerer.getLocalSdp().?); + defer allocator.free(answerer_sdp_z); + try testing.expect(rtc.rtcSetRemoteDescription(offerer.pc_id, answerer_sdp_z, "answer") >= 0); + + // Exchange ICE candidates + { + const cands = try answerer.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(offerer, z); + } + } + { + const cands = try offerer.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(answerer, z); + } + } + + // Wait for DataChannels to open + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, offerer, 10000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, answerer, 10000)); + + return .{ .offerer = offerer, .answerer = answerer }; +} + +/// Wait until a ChannelState has at least one message in its recv queue. +fn waitForRecv(cs: *webrtc.ChannelState, timeout_ms: u64) bool { + return waitFor(struct { + fn check(c: *webrtc.ChannelState) bool { + c.mutex.lock(); + defer c.mutex.unlock(); + return c.recv_queue.items.len > 0; + } + }.check, cs, timeout_ms); +} + +test "3-node mesh raw message exchange" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Create 3 pairs: Alice↔Bob, Alice↔Charlie, Bob↔Charlie + const ab = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(ab.offerer); + defer mgr.destroyChannel(ab.answerer); + + const ac = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(ac.offerer); + defer mgr.destroyChannel(ac.answerer); + + const bc = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(bc.offerer); + defer mgr.destroyChannel(bc.answerer); + + // Alias for clarity: + // ab.offerer = Alice's channel to Bob + // ab.answerer = Bob's channel to Alice + // ac.offerer = Alice's channel to Charlie + // ac.answerer = Charlie's channel to Alice + // bc.offerer = Bob's channel to Charlie + // bc.answerer = Charlie's channel to Bob + + // Send 6 unique messages (each node → each peer) + const msg_a_to_b = "Hello Bob, from Alice"; + const msg_a_to_c = "Hello Charlie, from Alice"; + const msg_b_to_a = "Hello Alice, from Bob"; + const msg_b_to_c = "Hello Charlie, from Bob"; + const msg_c_to_a = "Hello Alice, from Charlie"; + const msg_c_to_b = "Hello Bob, from Charlie"; + + _ = try mgr.send(ab.offerer, msg_a_to_b); + _ = try mgr.send(ac.offerer, msg_a_to_c); + _ = try mgr.send(ab.answerer, msg_b_to_a); + _ = try mgr.send(bc.offerer, msg_b_to_c); + _ = try mgr.send(ac.answerer, msg_c_to_a); + _ = try mgr.send(bc.answerer, msg_c_to_b); + + // Verify all 6 messages received + try testing.expect(waitForRecv(ab.answerer, 5000)); // Bob receives from Alice + try testing.expect(waitForRecv(ac.answerer, 5000)); // Charlie receives from Alice + try testing.expect(waitForRecv(ab.offerer, 5000)); // Alice receives from Bob + try testing.expect(waitForRecv(bc.answerer, 5000)); // Charlie receives from Bob + try testing.expect(waitForRecv(ac.offerer, 5000)); // Alice receives from Charlie + try testing.expect(waitForRecv(bc.offerer, 5000)); // Bob receives from Charlie + + // Pop and verify each message + const recv_b_from_a = ab.answerer.popRecvMessage().?; + defer allocator.free(recv_b_from_a.data); + try testing.expectEqualStrings(msg_a_to_b, recv_b_from_a.data); + + const recv_c_from_a = ac.answerer.popRecvMessage().?; + defer allocator.free(recv_c_from_a.data); + try testing.expectEqualStrings(msg_a_to_c, recv_c_from_a.data); + + const recv_a_from_b = ab.offerer.popRecvMessage().?; + defer allocator.free(recv_a_from_b.data); + try testing.expectEqualStrings(msg_b_to_a, recv_a_from_b.data); + + const recv_c_from_b = bc.answerer.popRecvMessage().?; + defer allocator.free(recv_c_from_b.data); + try testing.expectEqualStrings(msg_b_to_c, recv_c_from_b.data); + + const recv_a_from_c = ac.offerer.popRecvMessage().?; + defer allocator.free(recv_a_from_c.data); + try testing.expectEqualStrings(msg_c_to_a, recv_a_from_c.data); + + const recv_b_from_c = bc.offerer.popRecvMessage().?; + defer allocator.free(recv_b_from_c.data); + try testing.expectEqualStrings(msg_c_to_b, recv_b_from_c.data); +} + +test "3-node mesh with Noise encryption on one pair" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Create 3 pairs + const ab = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(ab.answerer); + defer mgr.destroyChannel(ab.offerer); + + const ac = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(ac.offerer); + defer mgr.destroyChannel(ac.answerer); + + const bc = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(bc.offerer); + defer mgr.destroyChannel(bc.answerer); + + // Wrap Alice↔Bob in Noise encryption + var alice_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, ab.offerer); + var bob_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, ab.answerer); + + const alice_transport = Transport.init(&alice_wrtc); + const bob_transport = Transport.init(&bob_wrtc); + + const alice_kp = noise.KeyPair.generate(); + const bob_kp = noise.KeyPair.generate(); + + const alice_sec = try allocator.create(SecureConnection); + defer allocator.destroy(alice_sec); + alice_sec.initWithTransport(alice_transport, alice_kp, allocator); + + const bob_sec = try allocator.create(SecureConnection); + defer allocator.destroy(bob_sec); + bob_sec.initWithTransport(bob_transport, bob_kp, allocator); + + // Run Noise XX handshake on threads + const HandshakeCtx = struct { + sec: *SecureConnection, + err: ?SecureError = null, + }; + + var alice_ctx = HandshakeCtx{ .sec = alice_sec }; + var bob_ctx = HandshakeCtx{ .sec = bob_sec }; + + const alice_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.initiateHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&alice_ctx}); + + const bob_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.acceptHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&bob_ctx}); + + alice_thread.join(); + bob_thread.join(); + + if (alice_ctx.err) |err| { + std.log.err("Alice handshake failed: {}", .{err}); + return error.TestUnexpectedResult; + } + if (bob_ctx.err) |err| { + std.log.err("Bob handshake failed: {}", .{err}); + return error.TestUnexpectedResult; + } + + // Verify Noise handshake + try testing.expect(alice_sec.isEncrypted()); + try testing.expect(bob_sec.isEncrypted()); + + const alice_remote = alice_sec.getRemotePublicKey().?; + const bob_remote = bob_sec.getRemotePublicKey().?; + try testing.expectEqualSlices(u8, &bob_kp.public, &alice_remote); + try testing.expectEqualSlices(u8, &alice_kp.public, &bob_remote); + try testing.expect(alice_sec.envelope_key != null); + try testing.expect(bob_sec.envelope_key != null); + + // Send encrypted message on Alice↔Bob + const encrypted_msg = "Encrypted mesh message: Alice to Bob"; + _ = try alice_sec.send(encrypted_msg); + + try testing.expect(waitForRecv(ab.answerer, 5000)); + + var recv_buf: [1024]u8 = undefined; + const decrypted = try bob_sec.receive(&recv_buf); + try testing.expectEqualStrings(encrypted_msg, decrypted); + + // Bob replies encrypted + const encrypted_reply = "Encrypted mesh reply: Bob to Alice"; + _ = try bob_sec.send(encrypted_reply); + + try testing.expect(waitForRecv(ab.offerer, 5000)); + + var reply_buf: [1024]u8 = undefined; + const reply_decrypted = try alice_sec.receive(&reply_buf); + try testing.expectEqualStrings(encrypted_reply, reply_decrypted); + + // Plaintext messages on other pairs (Alice↔Charlie, Bob↔Charlie) + const msg_a_to_c = "Plaintext: Alice to Charlie"; + const msg_c_to_a = "Plaintext: Charlie to Alice"; + const msg_b_to_c = "Plaintext: Bob to Charlie"; + const msg_c_to_b = "Plaintext: Charlie to Bob"; + + _ = try mgr.send(ac.offerer, msg_a_to_c); + _ = try mgr.send(ac.answerer, msg_c_to_a); + _ = try mgr.send(bc.offerer, msg_b_to_c); + _ = try mgr.send(bc.answerer, msg_c_to_b); + + try testing.expect(waitForRecv(ac.answerer, 5000)); + try testing.expect(waitForRecv(ac.offerer, 5000)); + try testing.expect(waitForRecv(bc.answerer, 5000)); + try testing.expect(waitForRecv(bc.offerer, 5000)); + + const recv_c_from_a = ac.answerer.popRecvMessage().?; + defer allocator.free(recv_c_from_a.data); + try testing.expectEqualStrings(msg_a_to_c, recv_c_from_a.data); + + const recv_a_from_c = ac.offerer.popRecvMessage().?; + defer allocator.free(recv_a_from_c.data); + try testing.expectEqualStrings(msg_c_to_a, recv_a_from_c.data); + + const recv_c_from_b = bc.answerer.popRecvMessage().?; + defer allocator.free(recv_c_from_b.data); + try testing.expectEqualStrings(msg_b_to_c, recv_c_from_b.data); + + const recv_b_from_c = bc.offerer.popRecvMessage().?; + defer allocator.free(recv_b_from_c.data); + try testing.expectEqualStrings(msg_c_to_b, recv_b_from_c.data); +} + +const Sha256 = std.crypto.hash.sha2.Sha256; + +/// Fill buffer with deterministic data unique to each chunk index. +fn fillDeterministic(buf: []u8, chunk_index: usize) void { + const seed: u64 = @as(u64, @intCast(chunk_index)) *% 0x517cc1b727220a95 +% 0x1; + var i: usize = 0; + while (i + 8 <= buf.len) : (i += 8) { + const val = seed +% @as(u64, @intCast(i)); + @memcpy(buf[i..][0..8], std.mem.asBytes(&val)); + } + while (i < buf.len) : (i += 1) { + buf[i] = @truncate(seed +% @as(u64, @intCast(i))); + } +} + +// File transfer constants (file-scope so sender thread can access them) +const xfer_total_size: usize = 1024 * 1024 * 1024; // 1GB +const xfer_chunk_size: usize = 64 * 1024; // 64KB +const xfer_total_chunks: usize = xfer_total_size / xfer_chunk_size; // 16384 + +const SendOneCtx = struct { + dc_id: c_int, + send_hash: [32]u8 = undefined, + err: ?anyerror = null, + + fn run(self: *SendOneCtx) void { + var hasher = Sha256.init(.{}); + var buf: [xfer_chunk_size]u8 = undefined; + const buf_high: c_int = 4 * 1024 * 1024; // backpressure threshold + var i: usize = 0; + while (i < xfer_total_chunks) : (i += 1) { + fillDeterministic(&buf, i); + hasher.update(&buf); + while (rtc.rtcGetBufferedAmount(self.dc_id) > buf_high) { + std.Thread.sleep(50 * std.time.ns_per_us); + } + if (rtc.rtcSendMessage(self.dc_id, &buf, @intCast(buf.len)) < 0) { + self.err = error.TestUnexpectedResult; + return; + } + } + hasher.final(&self.send_hash); + } +}; + +const RecvCtx = struct { + ch: *webrtc.ChannelState, + hash: [32]u8 = undefined, + + fn run(self: *RecvCtx) void { + var hasher = Sha256.init(.{}); + var count: usize = 0; + while (count < xfer_total_chunks) { + if (self.ch.popRecvMessage()) |msg| { + hasher.update(msg.data); + self.ch.allocator.free(msg.data); + count += 1; + } else { + std.Thread.sleep(10 * std.time.ns_per_us); + } + } + hasher.final(&self.hash); + } +}; + +test "3-node mesh file transfer - 1GB" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Alice shares file with Bob and Charlie simultaneously + const ab = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(ab.offerer); + defer mgr.destroyChannel(ab.answerer); + + const ac = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(ac.offerer); + defer mgr.destroyChannel(ac.answerer); + + var bob_recv = RecvCtx{ .ch = ab.answerer }; + var charlie_recv = RecvCtx{ .ch = ac.answerer }; + + var bob_send = SendOneCtx{ .dc_id = ab.offerer.dc_id.load(.acquire) }; + var charlie_send = SendOneCtx{ .dc_id = ac.offerer.dc_id.load(.acquire) }; + + const t_start = std.time.nanoTimestamp(); + + // 4 threads: 2 senders + 2 receivers — each SCTP pipe saturated independently + const bob_send_thread = try std.Thread.spawn(.{}, SendOneCtx.run, .{&bob_send}); + const charlie_send_thread = try std.Thread.spawn(.{}, SendOneCtx.run, .{&charlie_send}); + const bob_recv_thread = try std.Thread.spawn(.{}, RecvCtx.run, .{&bob_recv}); + const charlie_recv_thread = try std.Thread.spawn(.{}, RecvCtx.run, .{&charlie_recv}); + + bob_send_thread.join(); + charlie_send_thread.join(); + bob_recv_thread.join(); + charlie_recv_thread.join(); + + const elapsed_ns = std.time.nanoTimestamp() - t_start; + const elapsed_s = @as(f64, @floatFromInt(elapsed_ns)) / 1e9; + const throughput = @as(f64, @floatFromInt(xfer_total_size)) / elapsed_s / (1024 * 1024); + std.debug.print("\n1GB x2 peers: {d:.1}s — {d:.0} MB/s per peer, {d:.0} MB/s total\n", .{ elapsed_s, throughput, throughput * 2 }); + + if (bob_send.err) |err| { + std.log.err("Bob sender failed: {}", .{err}); + return error.TestUnexpectedResult; + } + if (charlie_send.err) |err| { + std.log.err("Charlie sender failed: {}", .{err}); + return error.TestUnexpectedResult; + } + + // Both senders generated identical data → hashes must match each other and receivers + try testing.expectEqualSlices(u8, &bob_send.send_hash, &charlie_send.send_hash); + try testing.expectEqualSlices(u8, &bob_send.send_hash, &bob_recv.hash); + try testing.expectEqualSlices(u8, &bob_send.send_hash, &charlie_recv.hash); +} + diff --git a/tests/integration/test_webrtc_noise.zig b/tests/integration/test_webrtc_noise.zig new file mode 100644 index 0000000..d1d621f --- /dev/null +++ b/tests/integration/test_webrtc_noise.zig @@ -0,0 +1,234 @@ +//! WebRTC + Noise Integration Test — verify Noise XX handshake works over +//! WebRTC DataChannel transport. +//! +//! This proves the full security stack works end-to-end: +//! 1. Two native WebRTC peers establish a DataChannel +//! 2. Wrap each in WebRTCChannelTransport → Transport vtable +//! 3. Create SecureConnection with initWithTransport (no socket) +//! 4. Run Noise XX handshake over WebRTC (blocking, on separate threads) +//! 5. Exchange encrypted messages +//! 6. Verify wire envelope key is derived +//! +//! Requires: libdatachannel.dylib available + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; +const core = @import("core"); +const network = @import("network"); +const noise = @import("noise"); +const Transport = core.transport.Transport; +const SecureConnection = network.SecureConnection; +const SecureError = network.secure_connection.Error; + +/// Wait for a condition with timeout (milliseconds). +fn waitFor(comptime predicate: anytype, ctx: anytype, timeout_ms: u64) bool { + var waited: u64 = 0; + const poll_ms: u64 = 10; + while (waited < timeout_ms) : (waited += poll_ms) { + if (predicate(ctx)) return true; + std.Thread.sleep(poll_ms * std.time.ns_per_ms); + } + return false; +} + +/// Establish a WebRTC DataChannel pair and return (alice_cs, bob_cs). +fn setupWebRTCPair(allocator: std.mem.Allocator, mgr: *webrtc.NativeWebRTCManager) !struct { alice: *webrtc.ChannelState, bob: *webrtc.ChannelState } { + const alice = try mgr.createOffer(null); + errdefer mgr.destroyChannel(alice); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, alice, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, alice, 5000)); + + const alice_sdp_z = try allocator.dupeZ(u8, alice.getLocalSdp().?); + defer allocator.free(alice_sdp_z); + + const bob = try mgr.acceptOffer(alice_sdp_z, null); + errdefer mgr.destroyChannel(bob); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, bob, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, bob, 5000)); + + const bob_sdp_z = try allocator.dupeZ(u8, bob.getLocalSdp().?); + defer allocator.free(bob_sdp_z); + try testing.expect(rtc.rtcSetRemoteDescription(alice.pc_id, bob_sdp_z, "answer") >= 0); + + // Exchange ICE candidates + { + const cands = try bob.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(alice, z); + } + } + { + const cands = try alice.drainLocalCandidates(allocator); + defer { + for (cands) |c| allocator.free(c); + if (cands.len > 0) allocator.free(cands); + } + for (cands) |cand| { + const z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(z); + mgr.addRemoteCandidate(bob, z); + } + } + + // Wait for DataChannels to open + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, alice, 10000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, bob, 10000)); + + return .{ .alice = alice, .bob = bob }; +} + +test "Noise XX handshake over WebRTC DataChannel" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // Step 1: Establish WebRTC DataChannel pair + const pair = try setupWebRTCPair(allocator, &mgr); + defer mgr.destroyChannel(pair.alice); + defer mgr.destroyChannel(pair.bob); + + // Step 2: Create WebRTC Transports + var alice_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, pair.alice); + var bob_wrtc = webrtc.WebRTCChannelTransport.init(&mgr, pair.bob); + + const alice_transport = Transport.init(&alice_wrtc); + const bob_transport = Transport.init(&bob_wrtc); + + // Step 3: Create Noise keypairs + const alice_kp = noise.KeyPair.generate(); + const bob_kp = noise.KeyPair.generate(); + + // Step 4: Create SecureConnections with Transport (no socket) + const alice_sec = try allocator.create(SecureConnection); + defer allocator.destroy(alice_sec); + alice_sec.initWithTransport(alice_transport, alice_kp, allocator); + + const bob_sec = try allocator.create(SecureConnection); + defer allocator.destroy(bob_sec); + bob_sec.initWithTransport(bob_transport, bob_kp, allocator); + + // Step 5: Run Noise handshake on separate threads (blocking) + const HandshakeCtx = struct { + sec: *SecureConnection, + err: ?SecureError = null, + }; + + var alice_ctx = HandshakeCtx{ .sec = alice_sec }; + var bob_ctx = HandshakeCtx{ .sec = bob_sec }; + + const alice_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.initiateHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&alice_ctx}); + + const bob_thread = try std.Thread.spawn(.{}, struct { + fn run(ctx: *HandshakeCtx) void { + ctx.sec.acceptHandshake() catch |err| { + ctx.err = err; + }; + } + }.run, .{&bob_ctx}); + + alice_thread.join(); + bob_thread.join(); + + // Check for errors + if (alice_ctx.err) |err| { + std.log.err("Alice handshake failed: {}", .{err}); + return error.TestUnexpectedResult; + } + if (bob_ctx.err) |err| { + std.log.err("Bob handshake failed: {}", .{err}); + return error.TestUnexpectedResult; + } + + // Step 6: Verify handshake completed + try testing.expect(alice_sec.isEncrypted()); + try testing.expect(bob_sec.isEncrypted()); + + // Verify remote keys + const alice_remote = alice_sec.getRemotePublicKey().?; + const bob_remote = bob_sec.getRemotePublicKey().?; + try testing.expectEqualSlices(u8, &bob_kp.public, &alice_remote); + try testing.expectEqualSlices(u8, &alice_kp.public, &bob_remote); + + // Verify envelope keys were derived + try testing.expect(alice_sec.envelope_key != null); + try testing.expect(bob_sec.envelope_key != null); + + // Step 7: Exchange encrypted messages + const plaintext = "encrypted over WebRTC via Noise"; + _ = try alice_sec.send(plaintext); + + // Wait for Bob to receive the encrypted message + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, pair.bob, 5000)); + + var recv_buf: [1024]u8 = undefined; + const decrypted = try bob_sec.receive(&recv_buf); + try testing.expectEqualStrings(plaintext, decrypted); + + // Bidirectional: Bob → Alice + const reply = "Noise reply over WebRTC"; + _ = try bob_sec.send(reply); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, pair.alice, 5000)); + + var reply_buf: [1024]u8 = undefined; + const reply_decrypted = try alice_sec.receive(&reply_buf); + try testing.expectEqualStrings(reply, reply_decrypted); +} diff --git a/tests/integration/test_webrtc_p2p_integration.zig b/tests/integration/test_webrtc_p2p_integration.zig new file mode 100644 index 0000000..eb68c83 --- /dev/null +++ b/tests/integration/test_webrtc_p2p_integration.zig @@ -0,0 +1,192 @@ +//! WebRTC P2P Integration Test — verify WebRTCChannelTransport works +//! as a PeerConnection transport, completing the T5.17 integration. +//! +//! Flow: +//! 1. Two native WebRTC peers establish a DataChannel (like loopback test) +//! 2. Wrap each ChannelState in a WebRTCChannelTransport +//! 3. Create PeerConnection using initWithTransport (no socket) +//! 4. Send/receive data through PeerConnection.transport_handle +//! 5. Verify PeerConnection.socket is null (WebRTC path) +//! +//! Requires: libdatachannel.dylib available + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; +const core = @import("core"); +const network = @import("network"); +const Transport = core.transport.Transport; +const PeerConnection = network.PeerConnection; + +/// Wait for a condition with timeout (milliseconds). +fn waitFor(comptime predicate: anytype, ctx: anytype, timeout_ms: u64) bool { + var waited: u64 = 0; + const poll_ms: u64 = 10; + while (waited < timeout_ms) : (waited += poll_ms) { + if (predicate(ctx)) return true; + std.Thread.sleep(poll_ms * std.time.ns_per_ms); + } + return false; +} + +test "WebRTC P2P integration: PeerConnection with WebRTCChannelTransport" { + if (!rtc.load()) return error.SkipZigTest; + + const allocator = testing.allocator; + rtc.rtcInitLogger(.warning, null); + + var mgr = webrtc.NativeWebRTCManager.init(allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + // --- Step 1: Establish WebRTC DataChannel between Alice and Bob --- + + const alice = try mgr.createOffer(null); + defer mgr.destroyChannel(alice); + + // Wait for Alice's SDP + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, alice, 5000)); + + // Wait for Alice's ICE gathering + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, alice, 5000)); + + const alice_sdp_z = try allocator.dupeZ(u8, alice.getLocalSdp().?); + defer allocator.free(alice_sdp_z); + + const bob = try mgr.acceptOffer(alice_sdp_z, null); + defer mgr.destroyChannel(bob); + + // Wait for Bob's SDP + ICE gathering + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.getLocalSdp() != null; + } + }.check, bob, 5000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.gathering_complete.load(.acquire); + } + }.check, bob, 5000)); + + // Exchange SDPs + const bob_sdp_z = try allocator.dupeZ(u8, bob.getLocalSdp().?); + defer allocator.free(bob_sdp_z); + + const result = rtc.rtcSetRemoteDescription(alice.pc_id, bob_sdp_z, "answer"); + try testing.expect(result >= 0); + + // Exchange ICE candidates: Bob → Alice + { + const bob_candidates = try bob.drainLocalCandidates(allocator); + defer { + for (bob_candidates) |c| allocator.free(c); + if (bob_candidates.len > 0) allocator.free(bob_candidates); + } + for (bob_candidates) |cand| { + const cand_z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(cand_z); + mgr.addRemoteCandidate(alice, cand_z); + } + } + + // Exchange ICE candidates: Alice → Bob + { + const alice_candidates = try alice.drainLocalCandidates(allocator); + defer { + for (alice_candidates) |c| allocator.free(c); + if (alice_candidates.len > 0) allocator.free(alice_candidates); + } + for (alice_candidates) |cand| { + const cand_z = allocator.dupeZ(u8, cand) catch continue; + defer allocator.free(cand_z); + mgr.addRemoteCandidate(bob, cand_z); + } + } + + // Wait for DataChannels to open + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, alice, 10000)); + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + return cs.dc_open.load(.acquire); + } + }.check, bob, 10000)); + + // --- Step 2: Wrap in WebRTCChannelTransport --- + + var alice_wrtc_transport = webrtc.WebRTCChannelTransport.init(&mgr, alice); + var bob_wrtc_transport = webrtc.WebRTCChannelTransport.init(&mgr, bob); + + const alice_transport = Transport.init(&alice_wrtc_transport); + const bob_transport = Transport.init(&bob_wrtc_transport); + + // --- Step 3: Create PeerConnections via initWithTransport --- + + const alice_pc = try PeerConnection.initWithTransport(allocator, alice_transport); + defer { + alice_pc.deinit(); + } + + const bob_pc = try PeerConnection.initWithTransport(allocator, bob_transport); + defer { + bob_pc.deinit(); + } + + // Verify: no socket associated + try testing.expect(alice_pc.socket == null); + try testing.expect(bob_pc.socket == null); + + // Verify: transport handle is connected state + try testing.expectEqual(core.transport.TransportState.connected, alice_pc.transport_handle.getState()); + try testing.expectEqual(core.transport.TransportState.connected, bob_pc.transport_handle.getState()); + + // --- Step 4: Send/receive through transport_handle --- + + const msg = "hello via PeerConnection"; + const sent = try alice_pc.transport_handle.send(msg); + try testing.expectEqual(msg.len, sent); + + // Wait for Bob to receive + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, bob, 5000)); + + // Read through transport_handle + var recv_buf: [256]u8 = undefined; + const received = try bob_pc.transport_handle.receive(&recv_buf); + try testing.expectEqualStrings(msg, recv_buf[0..received]); + + // --- Step 5: Verify bidirectional --- + + const reply = "reply via PeerConnection"; + _ = try bob_pc.transport_handle.send(reply); + + try testing.expect(waitFor(struct { + fn check(cs: *webrtc.ChannelState) bool { + cs.mutex.lock(); + defer cs.mutex.unlock(); + return cs.recv_queue.items.len > 0; + } + }.check, alice, 5000)); + + var reply_buf: [256]u8 = undefined; + const reply_received = try alice_pc.transport_handle.receive(&reply_buf); + try testing.expectEqualStrings(reply, reply_buf[0..reply_received]); +} diff --git a/tests/integration/test_webrtc_smoke.zig b/tests/integration/test_webrtc_smoke.zig new file mode 100644 index 0000000..d2da878 --- /dev/null +++ b/tests/integration/test_webrtc_smoke.zig @@ -0,0 +1,74 @@ +//! WebRTC Smoke Test — verify libdatachannel lifecycle works. +//! +//! Tests: rtcPreload → createPeerConnection → createDataChannel → close → delete → rtcCleanup +//! Requires: libdatachannel.dylib available (via WEBRTC_LIB_PATH or next to binary) + +const std = @import("std"); +const testing = std.testing; +const webrtc = @import("webrtc"); +const rtc = webrtc.rtc; + +test "webrtc smoke: lifecycle does not crash" { + // Load the WebRTC library at runtime + if (!rtc.load()) return error.SkipZigTest; + + rtc.rtcInitLogger(.warning, null); + rtc.rtcPreload(); + defer rtc.rtcCleanup(); + + // Create PeerConnection with no ICE servers (loopback) + var config = rtc.Configuration{}; + _ = &config; + + const pc_id = rtc.rtcCreatePeerConnection(&config); + try testing.expect(pc_id >= 0); + + // Create DataChannel + const dc_id = rtc.rtcCreateDataChannel(pc_id, "test"); + try testing.expect(dc_id >= 0); + + // Close and delete + _ = rtc.rtcClose(dc_id); + _ = rtc.rtcDelete(dc_id); + _ = rtc.rtcClosePeerConnection(pc_id); + _ = rtc.rtcDeletePeerConnection(pc_id); +} + +test "webrtc smoke: ChannelState init and deinit" { + const allocator = testing.allocator; + + var cs = webrtc.ChannelState.init(allocator, 42); + defer cs.deinit(); + + // Verify initial state + try testing.expectEqual(rtc.State.new, cs.state.load(.acquire)); + try testing.expect(!cs.dc_open.load(.acquire)); + try testing.expect(cs.getLocalSdp() == null); +} + +test "webrtc smoke: NativeWebRTCManager createOffer generates SDP" { + var mgr = webrtc.NativeWebRTCManager.init(testing.allocator) catch |err| switch (err) { + error.WebRTCUnavailable => return error.SkipZigTest, + }; + defer mgr.deinit(); + + rtc.rtcInitLogger(.warning, null); + + const cs = try mgr.createOffer(null); + defer mgr.destroyChannel(cs); + + // Wait for SDP to be generated (up to 2 seconds) + var waited: usize = 0; + while (cs.getLocalSdp() == null and waited < 200) : (waited += 1) { + std.Thread.sleep(10 * std.time.ns_per_ms); + } + + // Should have an SDP + const sdp = cs.getLocalSdp(); + try testing.expect(sdp != null); + + // SDP should contain "v=0" (SDP version line) + if (sdp) |s| { + try testing.expect(std.mem.indexOf(u8, s, "v=0") != null); + } +} diff --git a/tests/integration/test_webrtc_transfer.zig b/tests/integration/test_webrtc_transfer.zig new file mode 100644 index 0000000..ea632c0 --- /dev/null +++ b/tests/integration/test_webrtc_transfer.zig @@ -0,0 +1,776 @@ +//! Tests for the WebRTC file transfer v1 wire protocol. +//! +//! These tests validate the binary encoding/decoding of all v1 message +//! types independently of the demo application, serving as a protocol +//! specification test suite. + +const std = @import("std"); +const testing = std.testing; +const Sha256 = std.crypto.hash.sha2.Sha256; + +// Wire Protocol v1 constants (must match examples/webrtc_bridge_demo.zig + browser/demo/demo.js) +const PROTOCOL_VERSION: u8 = 0x01; +const APP_ID_FILE_OFFER: u8 = 0x20; +const APP_ID_FILE_ACCEPT: u8 = 0x21; +const APP_ID_FILE_CHUNK: u8 = 0x22; +const APP_ID_FILE_COMPLETE: u8 = 0x23; +const APP_ID_FILE_CANCEL: u8 = 0x24; +const APP_ID_FILE_RESUME: u8 = 0x25; +const APP_ID_FILE_PAUSE: u8 = 0x26; + +// ============================================================================ +// v1 Offer: [ver:1][xfer_id:8LE][name_len:2LE][name:N][size:8LE][sha256:32] +// ============================================================================ + +fn encodeOffer(buf: []u8, transfer_id: u64, name: []const u8, file_size: u64, hash: [32]u8) ?[]u8 { + const needed = 1 + 8 + 2 + name.len + 8 + 32; + if (buf.len < needed) return null; + + var pos: usize = 0; + buf[pos] = PROTOCOL_VERSION; + pos += 1; + std.mem.writeInt(u64, buf[pos..][0..8], transfer_id, .little); + pos += 8; + std.mem.writeInt(u16, buf[pos..][0..2], @intCast(name.len), .little); + pos += 2; + @memcpy(buf[pos..][0..name.len], name); + pos += name.len; + std.mem.writeInt(u64, buf[pos..][0..8], file_size, .little); + pos += 8; + @memcpy(buf[pos..][0..32], &hash); + pos += 32; + + return buf[0..pos]; +} + +const OfferFields = struct { + version: u8, + transfer_id: u64, + name: []const u8, + file_size: u64, + hash: [32]u8, +}; + +fn decodeOffer(data: []const u8) ?OfferFields { + if (data.len < 1) return null; + if (data[0] != PROTOCOL_VERSION) return null; + if (data.len < 1 + 8 + 2) return null; + + var pos: usize = 1; + const transfer_id = std.mem.readInt(u64, data[pos..][0..8], .little); + pos += 8; + const name_len = std.mem.readInt(u16, data[pos..][0..2], .little); + pos += 2; + if (data.len < pos + name_len + 8 + 32) return null; + const name = data[pos..][0..name_len]; + pos += name_len; + const file_size = std.mem.readInt(u64, data[pos..][0..8], .little); + pos += 8; + var hash: [32]u8 = undefined; + @memcpy(&hash, data[pos..][0..32]); + + return .{ + .version = PROTOCOL_VERSION, + .transfer_id = transfer_id, + .name = name, + .file_size = file_size, + .hash = hash, + }; +} + +// ============================================================================ +// v1 Accept: [xfer_id:8LE][name_len:2LE][name:N] +// ============================================================================ + +fn encodeAccept(buf: []u8, transfer_id: u64, name: []const u8) ?[]u8 { + const needed = 8 + 2 + name.len; + if (buf.len < needed) return null; + + std.mem.writeInt(u64, buf[0..8], transfer_id, .little); + std.mem.writeInt(u16, buf[8..10], @intCast(name.len), .little); + @memcpy(buf[10..][0..name.len], name); + + return buf[0..needed]; +} + +const AcceptFields = struct { + transfer_id: u64, + name: []const u8, +}; + +fn decodeAccept(data: []const u8) ?AcceptFields { + if (data.len < 10) return null; + const transfer_id = std.mem.readInt(u64, data[0..8], .little); + const name_len = std.mem.readInt(u16, data[8..10], .little); + if (data.len < 10 + name_len) return null; + return .{ + .transfer_id = transfer_id, + .name = data[10..][0..name_len], + }; +} + +// ============================================================================ +// v1 Chunk: [0xFF][0x22][xfer_id:8LE][offset:8LE][data:N] +// ============================================================================ + +fn encodeChunk(buf: []u8, transfer_id: u64, offset: u64, payload: []const u8) ?[]u8 { + const needed = 2 + 8 + 8 + payload.len; + if (buf.len < needed) return null; + + buf[0] = 0xFF; + buf[1] = APP_ID_FILE_CHUNK; + std.mem.writeInt(u64, buf[2..10], transfer_id, .little); + std.mem.writeInt(u64, buf[10..18], offset, .little); + @memcpy(buf[18..][0..payload.len], payload); + + return buf[0..needed]; +} + +const ChunkFields = struct { + transfer_id: u64, + offset: u64, + data: []const u8, +}; + +/// Decode chunk payload (after 0xFF + app_id prefix has been stripped). +fn decodeChunkPayload(payload: []const u8) ?ChunkFields { + if (payload.len < 16) return null; + return .{ + .transfer_id = std.mem.readInt(u64, payload[0..8], .little), + .offset = std.mem.readInt(u64, payload[8..16], .little), + .data = payload[16..], + }; +} + +// ============================================================================ +// v1 Complete: [0xFF][0x23][xfer_id:8LE][name_len:2LE][name:N] +// ============================================================================ + +fn encodeComplete(buf: []u8, transfer_id: u64, name: []const u8) ?[]u8 { + const needed = 2 + 8 + 2 + name.len; + if (buf.len < needed) return null; + + buf[0] = 0xFF; + buf[1] = APP_ID_FILE_COMPLETE; + std.mem.writeInt(u64, buf[2..10], transfer_id, .little); + std.mem.writeInt(u16, buf[10..12], @intCast(name.len), .little); + @memcpy(buf[12..][0..name.len], name); + + return buf[0..needed]; +} + +const CompleteFields = struct { + transfer_id: u64, + name: []const u8, +}; + +/// Decode complete payload (after 0xFF + app_id prefix has been stripped). +fn decodeCompletePayload(payload: []const u8) ?CompleteFields { + if (payload.len < 10) return null; + const transfer_id = std.mem.readInt(u64, payload[0..8], .little); + const name_len = std.mem.readInt(u16, payload[8..10], .little); + if (payload.len < 10 + name_len) return null; + return .{ + .transfer_id = transfer_id, + .name = payload[10..][0..name_len], + }; +} + +// ============================================================================ +// v1 Cancel: [0xFF][0x24][xfer_id:8LE][name_len:2LE][name:N] +// ============================================================================ + +fn encodeCancel(buf: []u8, transfer_id: u64, name: []const u8) ?[]u8 { + const needed = 2 + 8 + 2 + name.len; + if (buf.len < needed) return null; + + buf[0] = 0xFF; + buf[1] = APP_ID_FILE_CANCEL; + std.mem.writeInt(u64, buf[2..10], transfer_id, .little); + std.mem.writeInt(u16, buf[10..12], @intCast(name.len), .little); + @memcpy(buf[12..][0..name.len], name); + + return buf[0..needed]; +} + +// ============================================================================ +// v1 Resume: [xfer_id:8LE][last_offset:8LE] +// ============================================================================ + +fn encodeResume(buf: []u8, transfer_id: u64, last_offset: u64) ?[]u8 { + if (buf.len < 16) return null; + std.mem.writeInt(u64, buf[0..8], transfer_id, .little); + std.mem.writeInt(u64, buf[8..16], last_offset, .little); + return buf[0..16]; +} + +const ResumeFields = struct { + transfer_id: u64, + last_offset: u64, +}; + +fn decodeResume(data: []const u8) ?ResumeFields { + if (data.len < 16) return null; + return .{ + .transfer_id = std.mem.readInt(u64, data[0..8], .little), + .last_offset = std.mem.readInt(u64, data[8..16], .little), + }; +} + +// ============================================================================ +// Tests: Protocol Constants +// ============================================================================ + +test "protocol version is 0x01" { + try testing.expectEqual(@as(u8, 0x01), PROTOCOL_VERSION); +} + +test "app IDs are contiguous 0x20–0x26" { + try testing.expectEqual(@as(u8, 0x20), APP_ID_FILE_OFFER); + try testing.expectEqual(@as(u8, 0x21), APP_ID_FILE_ACCEPT); + try testing.expectEqual(@as(u8, 0x22), APP_ID_FILE_CHUNK); + try testing.expectEqual(@as(u8, 0x23), APP_ID_FILE_COMPLETE); + try testing.expectEqual(@as(u8, 0x24), APP_ID_FILE_CANCEL); + try testing.expectEqual(@as(u8, 0x25), APP_ID_FILE_RESUME); + try testing.expectEqual(@as(u8, 0x26), APP_ID_FILE_PAUSE); +} + +// ============================================================================ +// Tests: Offer Roundtrip +// ============================================================================ + +test "offer: encode/decode roundtrip" { + var buf: [1024]u8 = undefined; + const name = "photo.jpg"; + const xfer_id: u64 = 0xDEADBEEF_CAFEBABE; + const file_size: u64 = 1_073_741_824; // 1 GB + var hash: [32]u8 = undefined; + @memset(&hash, 0xAB); + + const encoded = encodeOffer(&buf, xfer_id, name, file_size, hash) orelse { + return error.EncodeFailed; + }; + + try testing.expectEqual(@as(usize, 1 + 8 + 2 + name.len + 8 + 32), encoded.len); + try testing.expectEqual(PROTOCOL_VERSION, encoded[0]); + + const decoded = decodeOffer(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(PROTOCOL_VERSION, decoded.version); + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqualStrings(name, decoded.name); + try testing.expectEqual(file_size, decoded.file_size); + try testing.expectEqualSlices(u8, &hash, &decoded.hash); +} + +test "offer: empty filename" { + var buf: [128]u8 = undefined; + const hash = [_]u8{0} ** 32; + const encoded = encodeOffer(&buf, 1, "", 0, hash) orelse return error.EncodeFailed; + const decoded = decodeOffer(encoded) orelse return error.DecodeFailed; + try testing.expectEqualStrings("", decoded.name); + try testing.expectEqual(@as(u64, 0), decoded.file_size); +} + +test "offer: max u64 values" { + var buf: [1024]u8 = undefined; + const hash = [_]u8{0xFF} ** 32; + const encoded = encodeOffer(&buf, std.math.maxInt(u64), "a", std.math.maxInt(u64), hash) orelse { + return error.EncodeFailed; + }; + const decoded = decodeOffer(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(std.math.maxInt(u64), decoded.transfer_id); + try testing.expectEqual(std.math.maxInt(u64), decoded.file_size); +} + +test "offer: decode rejects truncated data" { + try testing.expect(decodeOffer("") == null); + try testing.expect(decodeOffer(&[_]u8{0x01}) == null); // version only + try testing.expect(decodeOffer(&[_]u8{ 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) == null); // no name/size/hash +} + +test "offer: decode rejects wrong version" { + var buf: [128]u8 = undefined; + const hash = [_]u8{0} ** 32; + const encoded = encodeOffer(&buf, 1, "a", 10, hash) orelse return error.EncodeFailed; + // Corrupt version + var corrupted: [128]u8 = undefined; + @memcpy(corrupted[0..encoded.len], encoded); + corrupted[0] = 0x02; + try testing.expect(decodeOffer(corrupted[0..encoded.len]) == null); +} + +// ============================================================================ +// Tests: Accept Roundtrip +// ============================================================================ + +test "accept: encode/decode roundtrip" { + var buf: [1024]u8 = undefined; + const xfer_id: u64 = 42; + const name = "document.pdf"; + + const encoded = encodeAccept(&buf, xfer_id, name) orelse return error.EncodeFailed; + try testing.expectEqual(@as(usize, 8 + 2 + name.len), encoded.len); + + const decoded = decodeAccept(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqualStrings(name, decoded.name); +} + +test "accept: decode rejects truncated data" { + try testing.expect(decodeAccept("") == null); + try testing.expect(decodeAccept(&[_]u8{0} ** 9) == null); // 9 bytes < 10 minimum +} + +// ============================================================================ +// Tests: Chunk Roundtrip +// ============================================================================ + +test "chunk: encode/decode roundtrip" { + var buf: [256]u8 = undefined; + const xfer_id: u64 = 100; + const offset: u64 = 65536; + const payload = "hello chunk data"; + + const encoded = encodeChunk(&buf, xfer_id, offset, payload) orelse return error.EncodeFailed; + try testing.expectEqual(@as(usize, 2 + 8 + 8 + payload.len), encoded.len); + try testing.expectEqual(@as(u8, 0xFF), encoded[0]); + try testing.expectEqual(APP_ID_FILE_CHUNK, encoded[1]); + + // Decode from after the 0xFF + app_id prefix (what the app receives) + const decoded = decodeChunkPayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqual(offset, decoded.offset); + try testing.expectEqualStrings(payload, decoded.data); +} + +test "chunk: zero-length data" { + var buf: [32]u8 = undefined; + const encoded = encodeChunk(&buf, 1, 0, "") orelse return error.EncodeFailed; + const decoded = decodeChunkPayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(@as(u64, 0), decoded.offset); + try testing.expectEqualStrings("", decoded.data); +} + +test "chunk: decode rejects too-short payload" { + try testing.expect(decodeChunkPayload("") == null); + try testing.expect(decodeChunkPayload(&[_]u8{0} ** 15) == null); // 15 < 16 +} + +// ============================================================================ +// Tests: Complete Roundtrip +// ============================================================================ + +test "complete: encode/decode roundtrip" { + var buf: [256]u8 = undefined; + const xfer_id: u64 = 999; + const name = "video.mp4"; + + const encoded = encodeComplete(&buf, xfer_id, name) orelse return error.EncodeFailed; + try testing.expectEqual(@as(u8, 0xFF), encoded[0]); + try testing.expectEqual(APP_ID_FILE_COMPLETE, encoded[1]); + + const decoded = decodeCompletePayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqualStrings(name, decoded.name); +} + +test "complete: decode rejects truncated" { + try testing.expect(decodeCompletePayload("") == null); + try testing.expect(decodeCompletePayload(&[_]u8{0} ** 9) == null); +} + +// ============================================================================ +// Tests: Cancel Roundtrip +// ============================================================================ + +test "cancel: encode roundtrip via complete decoder" { + var buf: [256]u8 = undefined; + const xfer_id: u64 = 0x1234567890ABCDEF; + const name = "abandoned.bin"; + + const encoded = encodeCancel(&buf, xfer_id, name) orelse return error.EncodeFailed; + try testing.expectEqual(@as(u8, 0xFF), encoded[0]); + try testing.expectEqual(APP_ID_FILE_CANCEL, encoded[1]); + + // Cancel has same payload format as complete after the prefix + const decoded = decodeCompletePayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqualStrings(name, decoded.name); +} + +// ============================================================================ +// Tests: Resume Roundtrip +// ============================================================================ + +test "resume: encode/decode roundtrip" { + var buf: [32]u8 = undefined; + const xfer_id: u64 = 42; + const last_offset: u64 = 536_870_912; // 512 MB + + const encoded = encodeResume(&buf, xfer_id, last_offset) orelse return error.EncodeFailed; + try testing.expectEqual(@as(usize, 16), encoded.len); + + const decoded = decodeResume(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqual(last_offset, decoded.last_offset); +} + +test "resume: decode rejects truncated" { + try testing.expect(decodeResume("") == null); + try testing.expect(decodeResume(&[_]u8{0} ** 15) == null); +} + +test "resume: zero offset (restart from beginning)" { + var buf: [16]u8 = undefined; + const encoded = encodeResume(&buf, 1, 0) orelse return error.EncodeFailed; + const decoded = decodeResume(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(@as(u64, 0), decoded.last_offset); +} + +// ============================================================================ +// Tests: Legacy Format Detection +// ============================================================================ + +test "legacy offer detection: first byte != PROTOCOL_VERSION" { + // Legacy format starts with name_len:2LE — first byte is unlikely to be 0x01 + // for most filenames. The decoder checks data[0] == PROTOCOL_VERSION. + // A legacy offer for "hello.txt" (name_len=9) starts with 0x09, 0x00 + var buf: [64]u8 = undefined; + const name = "hello.txt"; + std.mem.writeInt(u16, buf[0..2], @intCast(name.len), .little); + @memcpy(buf[2..][0..name.len], name); + std.mem.writeInt(u64, buf[2 + name.len ..][0..8], 1024, .little); + + // Should NOT decode as v1 offer + try testing.expect(decodeOffer(buf[0 .. 2 + name.len + 8]) == null); +} + +test "legacy offer edge case: name_len == 1 collides with PROTOCOL_VERSION byte" { + // name_len=1 has first byte 0x01 == PROTOCOL_VERSION + // The v1 decoder should fail because the rest of the format doesn't match + var buf: [64]u8 = undefined; + buf[0] = 0x01; // name_len low byte = 1 (also looks like PROTOCOL_VERSION) + buf[1] = 0x00; // name_len high byte + buf[2] = 'a'; // name + std.mem.writeInt(u64, buf[3..11], 42, .little); + // Only 11 bytes — v1 needs at least 1+8+2=11 for header, then name+size+hash + // v1 decode: pos=1, reads 8 bytes xfer_id (buf[1..9]), then 2 bytes name_len (buf[9..11]) + // This will likely give a garbage name_len and fail the size check + const result = decodeOffer(buf[0..11]); + // It should either be null or give garbage — the point is it shouldn't silently succeed + // as a valid v1 offer for filename "a" with size 42 + if (result) |r| { + // If it decoded something, it definitely shouldn't match the legacy interpretation + try testing.expect(!std.mem.eql(u8, r.name, "a") or r.file_size != 42); + } +} + +// ============================================================================ +// Tests: SHA-256 Hash Verification +// ============================================================================ + +test "SHA-256: known test vector" { + // SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 + var hasher = Sha256.init(.{}); + const hash = hasher.finalResult(); + const expected = [_]u8{ + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, + 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, + 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, + 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, + }; + try testing.expectEqualSlices(u8, &expected, &hash); +} + +test "SHA-256: hash roundtrip through offer encoding" { + const data = "Hello, WebRTC file transfer!"; + var hasher = Sha256.init(.{}); + hasher.update(data); + const original_hash = hasher.finalResult(); + + var buf: [1024]u8 = undefined; + const encoded = encodeOffer(&buf, 1, "test.txt", data.len, original_hash) orelse { + return error.EncodeFailed; + }; + const decoded = decodeOffer(encoded) orelse return error.DecodeFailed; + try testing.expectEqualSlices(u8, &original_hash, &decoded.hash); +} + +// ============================================================================ +// Tests: Multi-Transfer Routing +// ============================================================================ + +test "multi-transfer: different transfer IDs in chunks are distinguishable" { + var buf1: [64]u8 = undefined; + var buf2: [64]u8 = undefined; + + const xfer1: u64 = 0x1111111111111111; + const xfer2: u64 = 0x2222222222222222; + + const enc1 = encodeChunk(&buf1, xfer1, 0, "chunk-a") orelse return error.EncodeFailed; + const enc2 = encodeChunk(&buf2, xfer2, 0, "chunk-b") orelse return error.EncodeFailed; + + const dec1 = decodeChunkPayload(enc1[2..]) orelse return error.DecodeFailed; + const dec2 = decodeChunkPayload(enc2[2..]) orelse return error.DecodeFailed; + + try testing.expect(dec1.transfer_id != dec2.transfer_id); + try testing.expectEqual(xfer1, dec1.transfer_id); + try testing.expectEqual(xfer2, dec2.transfer_id); + try testing.expectEqualStrings("chunk-a", dec1.data); + try testing.expectEqualStrings("chunk-b", dec2.data); +} + +test "multi-transfer: offer/accept/complete share transfer_id" { + const xfer_id: u64 = 0xAABBCCDDEEFF0011; + const name = "shared.dat"; + + var offer_buf: [1024]u8 = undefined; + var accept_buf: [256]u8 = undefined; + var complete_buf: [256]u8 = undefined; + + const hash = [_]u8{0} ** 32; + const offer_enc = encodeOffer(&offer_buf, xfer_id, name, 100, hash) orelse return error.EncodeFailed; + const accept_enc = encodeAccept(&accept_buf, xfer_id, name) orelse return error.EncodeFailed; + const complete_enc = encodeComplete(&complete_buf, xfer_id, name) orelse return error.EncodeFailed; + + const offer_dec = decodeOffer(offer_enc) orelse return error.DecodeFailed; + const accept_dec = decodeAccept(accept_enc) orelse return error.DecodeFailed; + const complete_dec = decodeCompletePayload(complete_enc[2..]) orelse return error.DecodeFailed; + + try testing.expectEqual(xfer_id, offer_dec.transfer_id); + try testing.expectEqual(xfer_id, accept_dec.transfer_id); + try testing.expectEqual(xfer_id, complete_dec.transfer_id); +} + +// ============================================================================ +// Tests: Full Transfer Lifecycle Simulation +// ============================================================================ + +test "lifecycle: offer → accept → chunks → complete with hash verification" { + const file_content = "The quick brown fox jumps over the lazy dog"; + + // 1. Compute file hash + var hasher = Sha256.init(.{}); + hasher.update(file_content); + const file_hash = hasher.finalResult(); + + // 2. Sender creates offer + const xfer_id: u64 = 12345; + const name = "fox.txt"; + var offer_buf: [1024]u8 = undefined; + const offer = encodeOffer(&offer_buf, xfer_id, name, file_content.len, file_hash) orelse { + return error.EncodeFailed; + }; + + // 3. Receiver decodes offer + const offer_dec = decodeOffer(offer) orelse return error.DecodeFailed; + try testing.expectEqualStrings(name, offer_dec.name); + try testing.expectEqual(@as(u64, file_content.len), offer_dec.file_size); + + // 4. Receiver sends accept + var accept_buf: [256]u8 = undefined; + const accept = encodeAccept(&accept_buf, offer_dec.transfer_id, offer_dec.name) orelse { + return error.EncodeFailed; + }; + const accept_dec = decodeAccept(accept) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, accept_dec.transfer_id); + + // 5. Sender sends file in chunks (simulate 16-byte chunks) + const chunk_size = 16; + var received_data: [file_content.len]u8 = undefined; + var offset: u64 = 0; + + while (offset < file_content.len) { + const end = @min(offset + chunk_size, file_content.len); + const chunk_data = file_content[offset..end]; + + var chunk_buf: [256]u8 = undefined; + const chunk = encodeChunk(&chunk_buf, xfer_id, offset, chunk_data) orelse { + return error.EncodeFailed; + }; + + // Receiver decodes chunk + const chunk_dec = decodeChunkPayload(chunk[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, chunk_dec.transfer_id); + try testing.expectEqual(offset, chunk_dec.offset); + + // Write to received buffer at correct offset + const dest_start: usize = @intCast(chunk_dec.offset); + @memcpy(received_data[dest_start..][0..chunk_dec.data.len], chunk_dec.data); + + offset = end; + } + + // 6. Sender sends complete + var complete_buf: [256]u8 = undefined; + const complete = encodeComplete(&complete_buf, xfer_id, name) orelse { + return error.EncodeFailed; + }; + const complete_dec = decodeCompletePayload(complete[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, complete_dec.transfer_id); + try testing.expectEqualStrings(name, complete_dec.name); + + // 7. Receiver verifies data integrity + try testing.expectEqualStrings(file_content, &received_data); + + // 8. Receiver computes SHA-256 and verifies against offer + var verify_hasher = Sha256.init(.{}); + verify_hasher.update(&received_data); + const computed_hash = verify_hasher.finalResult(); + try testing.expectEqualSlices(u8, &offer_dec.hash, &computed_hash); +} + +// ============================================================================ +// Tests: Cancel / Resume Scenarios +// ============================================================================ + +test "cancel interrupts transfer: cancel message carries correct transfer_id" { + const xfer_id: u64 = 0xFEDCBA9876543210; + const name = "interrupted.zip"; + + var buf: [256]u8 = undefined; + const encoded = encodeCancel(&buf, xfer_id, name) orelse return error.EncodeFailed; + + // Verify prefix + try testing.expectEqual(@as(u8, 0xFF), encoded[0]); + try testing.expectEqual(APP_ID_FILE_CANCEL, encoded[1]); + + // Decode payload + const decoded = decodeCompletePayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqualStrings(name, decoded.name); +} + +test "resume: resume message requests correct offset" { + const xfer_id: u64 = 42; + const resume_offset: u64 = 536_870_912; // 512 MB + + var buf: [16]u8 = undefined; + const encoded = encodeResume(&buf, xfer_id, resume_offset) orelse return error.EncodeFailed; + const decoded = decodeResume(encoded) orelse return error.DecodeFailed; + + try testing.expectEqual(xfer_id, decoded.transfer_id); + try testing.expectEqual(resume_offset, decoded.last_offset); +} + +// ============================================================================ +// Tests: Edge Cases +// ============================================================================ + +test "offer: maximum name length (512 bytes)" { + var buf: [1024]u8 = undefined; + const name = "a" ** 512; + const hash = [_]u8{0} ** 32; + const encoded = encodeOffer(&buf, 1, name, 0, hash) orelse return error.EncodeFailed; + const decoded = decodeOffer(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(@as(usize, 512), decoded.name.len); +} + +test "offer: file_size = 0 is valid" { + var buf: [128]u8 = undefined; + const hash = [_]u8{0} ** 32; + const encoded = encodeOffer(&buf, 1, "empty.txt", 0, hash) orelse return error.EncodeFailed; + const decoded = decodeOffer(encoded) orelse return error.DecodeFailed; + try testing.expectEqual(@as(u64, 0), decoded.file_size); +} + +test "chunk: large offset values" { + var buf: [64]u8 = undefined; + const offset: u64 = std.math.maxInt(u64) - 1; + const encoded = encodeChunk(&buf, 1, offset, "x") orelse return error.EncodeFailed; + const decoded = decodeChunkPayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(offset, decoded.offset); +} + +test "direct message routing: 0xFF prefix distinguishes direct from P2P framed" { + // Direct messages use 0xFF prefix, P2P framed messages don't + var chunk_buf: [64]u8 = undefined; + const chunk = encodeChunk(&chunk_buf, 1, 0, "data") orelse return error.EncodeFailed; + try testing.expectEqual(@as(u8, 0xFF), chunk[0]); + + // An accept message (P2P framed) does NOT start with 0xFF + var accept_buf: [64]u8 = undefined; + const accept = encodeAccept(&accept_buf, 1, "f") orelse return error.EncodeFailed; + try testing.expect(accept[0] != 0xFF); +} + +test "app_id byte distinguishes message types in direct path" { + var chunk_buf: [64]u8 = undefined; + var complete_buf: [64]u8 = undefined; + var cancel_buf: [64]u8 = undefined; + + const chunk = encodeChunk(&chunk_buf, 1, 0, "data") orelse return error.EncodeFailed; + const complete = encodeComplete(&complete_buf, 1, "f") orelse return error.EncodeFailed; + const cancel = encodeCancel(&cancel_buf, 1, "f") orelse return error.EncodeFailed; + + // All start with 0xFF but have different app_ids at byte 1 + try testing.expectEqual(@as(u8, 0xFF), chunk[0]); + try testing.expectEqual(@as(u8, 0xFF), complete[0]); + try testing.expectEqual(@as(u8, 0xFF), cancel[0]); + + try testing.expectEqual(APP_ID_FILE_CHUNK, chunk[1]); + try testing.expectEqual(APP_ID_FILE_COMPLETE, complete[1]); + try testing.expectEqual(APP_ID_FILE_CANCEL, cancel[1]); +} + +// ============================================================================ +// v1 Pause: [0xFF][0x26][xfer_id:8LE] +// ============================================================================ + +fn encodePause(buf: []u8, transfer_id: u64) ?[]u8 { + if (buf.len < 10) return null; + buf[0] = 0xFF; + buf[1] = APP_ID_FILE_PAUSE; + std.mem.writeInt(u64, buf[2..10], transfer_id, .little); + return buf[0..10]; +} + +const PauseFields = struct { + transfer_id: u64, +}; + +/// Decode pause payload (after 0xFF + app_id prefix has been stripped). +fn decodePausePayload(payload: []const u8) ?PauseFields { + if (payload.len < 8) return null; + return .{ + .transfer_id = std.mem.readInt(u64, payload[0..8], .little), + }; +} + +// ============================================================================ +// Tests: Pause Roundtrip +// ============================================================================ + +test "pause: encode/decode roundtrip" { + var buf: [16]u8 = undefined; + const xfer_id: u64 = 0xCAFEBABEDEADBEEF; + + const encoded = encodePause(&buf, xfer_id) orelse return error.EncodeFailed; + try testing.expectEqual(@as(usize, 10), encoded.len); + try testing.expectEqual(@as(u8, 0xFF), encoded[0]); + try testing.expectEqual(APP_ID_FILE_PAUSE, encoded[1]); + + // Decode from after the 0xFF + app_id prefix + const decoded = decodePausePayload(encoded[2..]) orelse return error.DecodeFailed; + try testing.expectEqual(xfer_id, decoded.transfer_id); +} + +test "pause: payload is exactly 8 bytes (xfer_id only)" { + var buf: [16]u8 = undefined; + const encoded = encodePause(&buf, 42) orelse return error.EncodeFailed; + // Total wire message is 10 bytes: [0xFF][0x26][xfer_id:8LE] + try testing.expectEqual(@as(usize, 10), encoded.len); + // Payload after prefix strip is 8 bytes + const payload = encoded[2..]; + try testing.expectEqual(@as(usize, 8), payload.len); +} + +test "pause: decode rejects truncated payload" { + try testing.expect(decodePausePayload("") == null); + try testing.expect(decodePausePayload(&[_]u8{0} ** 7) == null); // 7 < 8 +} + +test "pause: app_id is 0x26 and follows contiguous range" { + try testing.expectEqual(@as(u8, 0x26), APP_ID_FILE_PAUSE); + try testing.expectEqual(APP_ID_FILE_RESUME + 1, APP_ID_FILE_PAUSE); +}