Files
zigp2p/tests/integration/test_webrtc_e2e.zig
2026-02-19 11:38:56 -03:00

339 lines
12 KiB
Zig

//! 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
}