feat(postit): add native WebRTC calls with TURN IP masking
Replace the direct chat call panel with native Android and Linux WebRTC engines, enforce relay-only privacy, and cover consent, lifecycle, rendering and coturn interoperability. Document deployment and upgrade Avalonia to 12.1.6. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
384e330a78
commit
d812266ee0
28 changed files with 2568 additions and 61 deletions
140
src/PostIt/PostIt.Tests/AndroidWebRtcTestActivity.cs
Normal file
140
src/PostIt/PostIt.Tests/AndroidWebRtcTestActivity.cs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
#if ANDROID
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using PostIt.Android;
|
||||
using PostIt.Android.Services;
|
||||
using PostIt.Services;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
using Path = System.IO.Path;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
[Activity(Name = "fr.pschneider.postit.WebRtcTestActivity", Exported = true)]
|
||||
[SupportedOSPlatform("android26.0")]
|
||||
public sealed class AndroidWebRtcTestActivity : Activity
|
||||
{
|
||||
protected override async void OnCreate(Bundle? state)
|
||||
{
|
||||
base.OnCreate(state);
|
||||
var result = Path.Combine(FilesDir!.AbsolutePath, "webrtc-test-result.txt");
|
||||
File.WriteAllText(result, "RUNNING");
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(75));
|
||||
await RunAsync(Intent?.GetIntExtra("port", 0) ?? 0, timeout.Token);
|
||||
File.WriteAllText(result, "PASS\nnative WebRTC media and cleanup complete");
|
||||
}
|
||||
catch (Exception error) { File.WriteAllText(result, "FAIL\n" + error); }
|
||||
finally { Finish(); }
|
||||
}
|
||||
|
||||
private async Task RunAsync(int port, CancellationToken ct)
|
||||
{
|
||||
if (port is < 1024 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
||||
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
|
||||
while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View is null)
|
||||
await Task.Delay(100, ct);
|
||||
using var socket = new TcpClient();
|
||||
await socket.ConnectAsync("127.0.0.1", port, ct);
|
||||
using var stream = socket.GetStream();
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8, false, 4096, leaveOpen: true);
|
||||
using var writer = new StreamWriter(stream, new UTF8Encoding(false), 4096, leaveOpen: true) { AutoFlush = true };
|
||||
using var output = new SemaphoreSlim(1);
|
||||
var callbackFailure = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
async Task EmitAsync(object value)
|
||||
{
|
||||
await output.WaitAsync(ct);
|
||||
try { await writer.WriteLineAsync(JsonSerializer.Serialize(value, new JsonSerializerOptions(JsonSerializerDefaults.Web))); }
|
||||
finally { output.Release(); }
|
||||
}
|
||||
void Emit(object value) => _ = EmitObservedAsync(value);
|
||||
async Task EmitObservedAsync(object value)
|
||||
{
|
||||
try { await EmitAsync(value); }
|
||||
catch (Exception error) { callbackFailure.TrySetException(error); }
|
||||
}
|
||||
var navigation = ((App)Avalonia.Application.Current!).View!.FindControl<NavigationPage>("NavRoot")
|
||||
?? throw new InvalidOperationException("Main navigation unavailable.");
|
||||
AndroidWebRtcMedia? media = null;
|
||||
var attached = false;
|
||||
try
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(async () =>
|
||||
{
|
||||
media = new AndroidWebRtcMedia();
|
||||
var grid = new Grid { RowDefinitions = new RowDefinitions("*,*") };
|
||||
grid.Children.Add(media.LocalVideo);
|
||||
Grid.SetRow(media.RemoteVideo, 1);
|
||||
grid.Children.Add(media.RemoteVideo);
|
||||
await navigation.PushAsync(new ContentPage { Content = grid });
|
||||
attached = true;
|
||||
});
|
||||
var peer = media ?? throw new InvalidOperationException("Native UI unavailable.");
|
||||
peer.Signal += signal => Emit(new { type = "signal", signal });
|
||||
peer.StatusChanged += status =>
|
||||
{
|
||||
Emit(new { type = "status", status });
|
||||
if (status.LocalVideoRendered) Emit(new { type = "rendered", target = "local", size = 1_000 });
|
||||
if (status.RemoteVideoRendered) Emit(new { type = "rendered", target = "remote", size = 1_000 });
|
||||
};
|
||||
while (true)
|
||||
{
|
||||
var read = reader.ReadLineAsync(ct).AsTask();
|
||||
var completed = await Task.WhenAny(read, peer.Completion, callbackFailure.Task);
|
||||
if (completed != read)
|
||||
{
|
||||
await completed;
|
||||
throw new IOException("Native WebRTC stopped unexpectedly.");
|
||||
}
|
||||
var line = await read;
|
||||
if (line is null) throw new IOException("Test signaling disconnected.");
|
||||
using var document = JsonDocument.Parse(line);
|
||||
var root = document.RootElement;
|
||||
switch (root.GetProperty("command").GetString())
|
||||
{
|
||||
case "start":
|
||||
var configuration = root.GetProperty("configuration").Deserialize<WebRtcMediaConfiguration>(
|
||||
new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
|
||||
var camera = AndroidLanCallMedia.GetDevices().Cameras.FirstOrDefault(c => c.Name == "Camera avant")
|
||||
?? throw new InvalidOperationException("Front camera required.");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => peer.StartAsync(
|
||||
configuration with { Camera = camera.Value, Microphone = "microphone" }, ct));
|
||||
break;
|
||||
case "signal":
|
||||
var signal = root.GetProperty("signal").Deserialize<CallSignal>(
|
||||
new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
|
||||
await peer.HandleSignalAsync(signal, ct);
|
||||
break;
|
||||
case "close":
|
||||
await Dispatcher.UIThread.InvokeAsync(async () => await peer.DisposeAsync());
|
||||
await EmitAsync(new { type = "closed" });
|
||||
return;
|
||||
default: throw new InvalidOperationException("Unknown test command.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
await EmitAsync(new { type = "error", message = error.ToString() });
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (media is not null) await Dispatcher.UIThread.InvokeAsync(async () => await media.DisposeAsync());
|
||||
if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
267
src/PostIt/PostIt.Tests/Native/webrtc_media_test.py
Normal file
267
src/PostIt/PostIt.Tests/Native/webrtc_media_test.py
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
"""Real GStreamer/coturn regression. No camera, account or public service is used."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import queue
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
ENGINE = Path(__file__).resolve().parents[2] / "PostIt/Services/WebRtc/gstreamer_peer.py"
|
||||
|
||||
|
||||
class AndroidPeer:
|
||||
"""Debug Activity over an adb-reversed, loopback-only test command socket."""
|
||||
def __init__(self):
|
||||
self.adb = [os.environ.get("POSTIT_ADB", "adb")]
|
||||
if os.environ.get("POSTIT_ANDROID_SERIAL"):
|
||||
self.adb += ["-s", os.environ["POSTIT_ANDROID_SERIAL"]]
|
||||
self.exited = threading.Event()
|
||||
self.reversed = []
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
listener.settimeout(35)
|
||||
port = listener.getsockname()[1]
|
||||
self.reverse(port)
|
||||
try:
|
||||
subprocess.run(self.adb + ["shell", "am", "start", "-f", "0x18000000", "-n",
|
||||
"fr.pschneider.postit/.WebRtcTestActivity", "--ei", "port", str(port)],
|
||||
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=10)
|
||||
self.socket, _ = listener.accept()
|
||||
except BaseException:
|
||||
self.remove_reverses()
|
||||
raise
|
||||
self.input = self.socket.makefile("w", encoding="utf-8")
|
||||
self.output = self.socket.makefile("r", encoding="utf-8")
|
||||
self.stdin = self.input
|
||||
self.stdout = self.read()
|
||||
self.stderr = io.StringIO()
|
||||
|
||||
def reverse(self, port):
|
||||
subprocess.run(self.adb + ["reverse", f"tcp:{port}", f"tcp:{port}"], check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10)
|
||||
self.reversed.append(port)
|
||||
|
||||
def remove_reverses(self):
|
||||
for port in self.reversed:
|
||||
subprocess.run(self.adb + ["reverse", "--remove", f"tcp:{port}"], check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10)
|
||||
self.reversed.clear()
|
||||
|
||||
def read(self):
|
||||
try:
|
||||
yield from self.output
|
||||
finally:
|
||||
self.output.close()
|
||||
self.exited.set()
|
||||
|
||||
def poll(self):
|
||||
return 0 if self.exited.is_set() else None
|
||||
|
||||
def wait(self, timeout=None):
|
||||
if not self.exited.wait(timeout):
|
||||
raise subprocess.TimeoutExpired("Android test peer", timeout)
|
||||
self.socket.close()
|
||||
self.remove_reverses()
|
||||
return 0
|
||||
|
||||
def kill(self):
|
||||
self.socket.shutdown(socket.SHUT_RDWR)
|
||||
self.socket.close()
|
||||
|
||||
|
||||
class NativeWebRtcTests(unittest.TestCase):
|
||||
def run_pair(self, relay, unavailable=False, android=False, android_caller=False):
|
||||
processes = []
|
||||
events = queue.Queue()
|
||||
errors = []
|
||||
server = None
|
||||
server_log = None
|
||||
with tempfile.TemporaryDirectory(prefix="postit-turn-") as directory:
|
||||
try:
|
||||
servers = []
|
||||
if relay:
|
||||
binary = os.environ.get("POSTIT_TURN_SERVER", shutil.which("turnserver"))
|
||||
self.assertTrue(binary, "Install coturn or set POSTIT_TURN_SERVER")
|
||||
with socket.socket() as reservation:
|
||||
reservation.bind(("127.0.0.1", 0))
|
||||
port = reservation.getsockname()[1]
|
||||
secret = secrets.token_hex(32)
|
||||
username = str(int(time.time()) + 600) + ":native-test"
|
||||
password = base64.b64encode(hmac.new(secret.encode(), username.encode(), hashlib.sha1).digest()).decode()
|
||||
server_log = open(Path(directory) / "coturn.log", "w+")
|
||||
server = subprocess.Popen([
|
||||
binary, "-n", "--listening-ip=127.0.0.1", "--relay-ip=127.0.0.1",
|
||||
"--listening-port=" + str(port), "--min-port=52000", "--max-port=52100",
|
||||
"--realm=postit-native-test", "--use-auth-secret", "--static-auth-secret=" + secret,
|
||||
"--allow-loopback-peers", "--no-multicast-peers", "--no-tls", "--no-dtls",
|
||||
"--no-cli", "--relay-threads=1", "--pidfile=" + directory + "/turn.pid",
|
||||
"--log-file=stdout"
|
||||
], stdout=server_log, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic() + 10
|
||||
while True:
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
|
||||
break
|
||||
except OSError:
|
||||
if time.monotonic() > deadline or server.poll() is not None:
|
||||
server_log.seek(0)
|
||||
self.fail("coturn failed to start: " + server_log.read()[-2000:])
|
||||
time.sleep(0.1)
|
||||
if unavailable:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
servers = [{"urls": [f"turn:127.0.0.1:{port}?transport=tcp"],
|
||||
"username": username, "credential": password}]
|
||||
|
||||
def read(index, process):
|
||||
for line in process.stdout:
|
||||
try:
|
||||
message = json.loads(line)
|
||||
if message.get("type") == "frame":
|
||||
events.put((index, {"type": "rendered", "target": message["target"],
|
||||
"size": len(base64.b64decode(message["data"]))}))
|
||||
else:
|
||||
events.put((index, message))
|
||||
except Exception as error:
|
||||
errors.append(str(error))
|
||||
|
||||
def stderr(process):
|
||||
for line in process.stderr:
|
||||
errors.append(line.rstrip())
|
||||
|
||||
for index in range(2):
|
||||
if android and index == 1:
|
||||
process = AndroidPeer()
|
||||
if relay:
|
||||
process.reverse(port)
|
||||
else:
|
||||
process = subprocess.Popen([sys.executable, "-X", "faulthandler", "-u", str(ENGINE)],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, bufsize=1)
|
||||
processes.append(process)
|
||||
threading.Thread(target=read, args=(index, process), daemon=True).start()
|
||||
threading.Thread(target=stderr, args=(process,), daemon=True).start()
|
||||
self.send(process, {"command": "start", "configuration": {
|
||||
"iceServers": servers, "relayOnly": relay,
|
||||
"caller": index == (1 if android_caller else 0),
|
||||
"camera": "test", "microphone": "test"}})
|
||||
stats = {}
|
||||
rendered = set()
|
||||
candidates = 0
|
||||
descriptions = set()
|
||||
started = time.monotonic()
|
||||
deadline = started + (12 if unavailable else 35)
|
||||
while time.monotonic() < deadline:
|
||||
self.assertTrue(all(p.poll() is None for p in processes),
|
||||
f"Native peer exited: {[p.poll() for p in processes]}, {errors[-20:]}")
|
||||
try:
|
||||
index, message = events.get(timeout=0.5)
|
||||
except queue.Empty:
|
||||
self.assertTrue(all(p.poll() is None for p in processes), str(errors[-10:]))
|
||||
continue
|
||||
kind = message["type"]
|
||||
if kind == "error":
|
||||
self.fail(message["message"] + "\n" + str(errors[-10:]))
|
||||
if kind == "signal":
|
||||
signal = message["signal"]
|
||||
if relay:
|
||||
candidate = signal.get("candidate")
|
||||
if candidate:
|
||||
tokens = candidate.split()
|
||||
self.assertEqual("relay", tokens[7])
|
||||
if "raddr" in tokens:
|
||||
self.assertIn(tokens[tokens.index("raddr") + 1], ("0.0.0.0", "::"))
|
||||
for line in (signal.get("sdp") or "").splitlines():
|
||||
if line.startswith("a=candidate:"):
|
||||
self.assertEqual("relay", line.split()[7])
|
||||
if line.startswith(("o=", "c=")):
|
||||
self.assertIn(line.split()[-1], ("0.0.0.0", "::", "127.0.0.1"))
|
||||
if signal["kind"] == "candidate":
|
||||
candidates += 1
|
||||
else:
|
||||
descriptions.add((index, signal["kind"]))
|
||||
self.send(processes[1 - index], {"command": "signal", "signal": signal})
|
||||
if kind == "rendered" and message["size"] > 100:
|
||||
rendered.add((index, message["target"]))
|
||||
if kind == "status":
|
||||
stats[index] = message["status"]
|
||||
if unavailable:
|
||||
self.assertNotEqual("connected", message["status"]["connectionState"])
|
||||
self.assertEqual(0, message["status"]["audioPackets"])
|
||||
self.assertEqual(0, message["status"]["videoFrames"])
|
||||
elif time.monotonic() - started >= 10 and len(stats) == 2 and len(rendered) == 4 and all(
|
||||
s["connectionState"] == "connected" and s["audioPackets"] > 100
|
||||
and s["videoFrames"] >= 100 for s in stats.values()
|
||||
):
|
||||
if relay:
|
||||
self.assertTrue(all(s["localCandidateType"] == "relay" for s in stats.values()))
|
||||
self.assertGreater(candidates, 0)
|
||||
print(f"\nMedia verified: relay={relay}, android={android}, "
|
||||
f"androidCaller={android_caller}, stats={stats}, rendered={len(rendered)}",
|
||||
flush=True)
|
||||
return
|
||||
if unavailable:
|
||||
caller = 1 if android_caller else 0
|
||||
self.assertEqual({(caller, "offer"), (1 - caller, "answer")}, descriptions)
|
||||
self.assertEqual({0, 1}, set(stats))
|
||||
self.assertTrue(all((index, "local") in rendered for index in range(2)))
|
||||
self.assertEqual(0, candidates, "TURN failure must never disclose direct candidates")
|
||||
self.assertFalse(any(target == "remote" for _, target in rendered))
|
||||
return
|
||||
self.fail(f"No bidirectional decoded/rendered media: {stats}, {rendered}, {errors[-12:]}")
|
||||
finally:
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
self.send(process, {"command": "close"})
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
for stream in (process.stdin, process.stdout, process.stderr):
|
||||
stream.close()
|
||||
if server is not None and server.poll() is None:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
if server_log is not None:
|
||||
server_log.close()
|
||||
|
||||
@staticmethod
|
||||
def send(process, message):
|
||||
process.stdin.write(json.dumps(message) + "\n")
|
||||
process.stdin.flush()
|
||||
|
||||
def test_direct_bidirectional_media(self):
|
||||
self.run_pair(False)
|
||||
|
||||
def test_relay_bidirectional_media_and_no_address_disclosure(self):
|
||||
self.run_pair(True)
|
||||
|
||||
def test_turn_unavailable_never_falls_back_to_direct(self):
|
||||
self.run_pair(True, unavailable=True)
|
||||
|
||||
@unittest.skipUnless(os.environ.get("POSTIT_TEST_ANDROID_WEBRTC") == "1", "Requires installed Debug APK and adb device")
|
||||
def test_android_linux_relay_bidirectional_media(self):
|
||||
for caller in (False, True):
|
||||
with self.subTest(android_caller=caller):
|
||||
self.run_pair(True, android=True, android_caller=caller)
|
||||
|
||||
@unittest.skipUnless(os.environ.get("POSTIT_TEST_ANDROID_WEBRTC") == "1", "Requires installed Debug APK and adb device")
|
||||
def test_android_turn_unavailable_never_falls_back_to_direct(self):
|
||||
self.run_pair(True, unavailable=True, android=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -18,6 +18,7 @@
|
|||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Avalonia.Headless" />
|
||||
<PackageReference Include="Avalonia.Headless.XUnit" />
|
||||
<PackageReference Include="Avalonia.Skia" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
|
|
|||
|
|
@ -7,10 +7,14 @@ namespace PostIt.Tests;
|
|||
|
||||
public class TestAppBuilder
|
||||
{
|
||||
public static AppBuilder BuildAvaloniaApp() =>
|
||||
AppBuilder.Configure<PostIt.App>()
|
||||
.UseHeadless(new AvaloniaHeadlessPlatformOptions
|
||||
{
|
||||
UseHeadlessDrawing = true
|
||||
});
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
{
|
||||
var nativeMedia = System.Environment.GetEnvironmentVariable("POSTIT_TEST_NATIVE_WEBRTC") == "1";
|
||||
var builder = AppBuilder.Configure<PostIt.App>();
|
||||
if (nativeMedia) builder.UseSkia();
|
||||
return builder.UseHeadless(new AvaloniaHeadlessPlatformOptions
|
||||
{
|
||||
UseHeadlessDrawing = !nativeMedia
|
||||
});
|
||||
}
|
||||
}
|
||||
294
src/PostIt/PostIt.Tests/WebRtcCallViewModelTests.cs
Normal file
294
src/PostIt/PostIt.Tests/WebRtcCallViewModelTests.cs
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
using Avalonia.Controls;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Threading;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels.Chat;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
public sealed class WebRtcCallViewModelTests
|
||||
{
|
||||
private static readonly CallIceServer[] Turn = [new(["turn:localhost:3478"], "temporary", "password")];
|
||||
private const string Sdp = "v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\nc=IN IP4 0.0.0.0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n";
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Outgoing_waits_for_acceptance_and_passes_server_policy_to_native_engine(bool relay)
|
||||
{
|
||||
var signaling = new Signaling(relay);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
vm.AllowAddressDisclosure = !relay;
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
Assert.True(vm.Busy);
|
||||
Assert.Null(media.Configuration);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
Assert.Equal(relay, media.Configuration!.RelayOnly);
|
||||
Assert.True(media.Configuration.Caller);
|
||||
Assert.Same(Turn, media.Configuration.IceServers);
|
||||
media.Emit(new("offer", Sdp: Sdp));
|
||||
await WaitAsync(() => signaling.Sent.Count == 1);
|
||||
signaling.Receive(new("answer", Sdp: Sdp));
|
||||
await WaitAsync(() => media.Received.Count == 1);
|
||||
await vm.HangupAsync();
|
||||
Assert.True(media.Disposed);
|
||||
Assert.Null(vm.LocalVideo);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Incoming_relay_needs_acceptance_but_never_requires_IP_disclosure()
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
signaling.Invite();
|
||||
await WaitAsync(() => vm.Incoming);
|
||||
Assert.False(vm.AllowAddressDisclosure);
|
||||
Assert.Null(media.Configuration);
|
||||
await vm.AcceptCommand.ExecuteAsync(null);
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
Assert.False(media.Configuration!.Caller);
|
||||
media.Report(new("connected", "relay", 20, 20));
|
||||
await WaitAsync(() => vm.Status.Contains("IP masquee"));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Direct_call_without_consent_ends_before_any_capture()
|
||||
{
|
||||
var signaling = new Signaling(false);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
Assert.Null(media.Configuration);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains("consentez", vm.Status);
|
||||
Assert.Single(signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Missing_TURN_or_policy_downgrade_never_creates_a_native_engine(bool downgrade)
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var created = false;
|
||||
await using var vm = new WebRtcCallViewModel(signaling, () =>
|
||||
{
|
||||
created = true;
|
||||
throw new InvalidOperationException("Should not create media");
|
||||
})
|
||||
{ Camera = new("Camera", "camera"), Microphone = new("Mic", "default"), Target = "bob", Room = "General" };
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready(downgrade ? signaling.Call with { RelayOnly = false } : null,
|
||||
downgrade ? Turn : []);
|
||||
await WaitAsync(() => !vm.Busy);
|
||||
Assert.False(created);
|
||||
Assert.Single(signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData("hangup")]
|
||||
[InlineData("interrupted")]
|
||||
[InlineData("ended")]
|
||||
[InlineData("background")]
|
||||
[InlineData("dispose")]
|
||||
public async Task All_termination_paths_cancel_in_progress_native_startup(string reason)
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media { DelayStartup = true };
|
||||
await using var vm = Configure(signaling, media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
switch (reason)
|
||||
{
|
||||
case "hangup": await vm.HangupAsync(); break;
|
||||
case "interrupted": signaling.Disconnect(); break;
|
||||
case "ended": signaling.End(); break;
|
||||
case "background": Platform.SuspendPlayback(); break;
|
||||
case "dispose": await vm.DisposeAsync(); break;
|
||||
}
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Null(vm.RemoteVideo);
|
||||
Assert.True(media.StartupCancelled);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData("host")]
|
||||
[InlineData("srflx")]
|
||||
[InlineData(null)]
|
||||
public async Task Nonrelay_selected_path_is_rejected_and_media_is_stopped(string? candidateType)
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
media.Report(new("connected", candidateType, 20, 20));
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.Contains("chemin ICE", vm.Status);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Leaking_candidate_is_not_sent_and_fails_closed()
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
media.Emit(new("candidate", Candidate: "candidate:1 1 UDP 1 192.0.2.1 1234 typ host",
|
||||
SdpMid: "0", SdpMLineIndex: 0));
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.Empty(signaling.Sent);
|
||||
Assert.Contains("candidat", vm.Status);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Native_failure_is_visible_and_ends_the_server_call()
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
await vm.InviteCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
media.Fail();
|
||||
await WaitAsync(() => media.Disposed);
|
||||
Assert.Contains("native failure", vm.Status);
|
||||
Assert.Single(signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("candidate:1 1 UDP 1 192.0.2.1 1234 typ host")]
|
||||
[InlineData("candidate:1 1 UDP 1 192.0.2.1 1234 typ srflx")]
|
||||
[InlineData("candidate:1 1 UDP 1 192.0.2.1 1234 typ relay raddr 198.51.100.1 rport 1234")]
|
||||
public void Privacy_rejects_nonrelay_or_related_address_leaks(string candidate) =>
|
||||
Assert.Throws<InvalidOperationException>(() => WebRtcPrivacy.ValidateSignal(
|
||||
new("candidate", Candidate: candidate, SdpMid: "0", SdpMLineIndex: 0), true));
|
||||
|
||||
[Fact]
|
||||
public void Privacy_accepts_redacted_relay_and_rejects_SDP_address_leaks()
|
||||
{
|
||||
WebRtcPrivacy.ValidateSignal(new("candidate",
|
||||
Candidate: "candidate:1 1 UDP 1 192.0.2.1 1234 typ relay raddr 0.0.0.0 rport 0",
|
||||
SdpMid: "0", SdpMLineIndex: 0), true);
|
||||
WebRtcPrivacy.ValidateSignal(new("offer", Sdp: Sdp), true);
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
WebRtcPrivacy.ValidateSignal(new("offer", Sdp: Sdp.Replace("0.0.0.0", "198.51.100.1")), true));
|
||||
}
|
||||
|
||||
public static bool NativeMediaAvailable => OperatingSystem.IsLinux() &&
|
||||
Environment.GetEnvironmentVariable("POSTIT_TEST_NATIVE_WEBRTC") == "1";
|
||||
|
||||
[AvaloniaFact(Skip = "Requires Linux GStreamer/libnice and POSTIT_TEST_NATIVE_WEBRTC=1",
|
||||
SkipUnless = nameof(NativeMediaAvailable))]
|
||||
public async Task Linux_native_adapters_render_remote_bitmaps_and_receive_audio_in_both_directions()
|
||||
{
|
||||
await using var caller = new LinuxWebRtcMedia();
|
||||
await using var callee = new LinuxWebRtcMedia();
|
||||
var errors = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
void Forward(IWebRtcMedia destination, CallSignal signal) => Dispatcher.UIThread.Post(async () =>
|
||||
{
|
||||
try { await destination.HandleSignalAsync(signal, timeout.Token); }
|
||||
catch (Exception error) { errors.TrySetException(error); }
|
||||
});
|
||||
caller.Signal += signal => Forward(callee, signal);
|
||||
callee.Signal += signal => Forward(caller, signal);
|
||||
WebRtcMediaStatus? callerStatus = null, calleeStatus = null;
|
||||
caller.StatusChanged += status => callerStatus = status;
|
||||
callee.StatusChanged += status => calleeStatus = status;
|
||||
await callee.StartAsync(new([], false, false, "test", "test"), timeout.Token);
|
||||
await caller.StartAsync(new([], false, true, "test", "test"), timeout.Token);
|
||||
while (callerStatus is not { HasRemoteMedia: true } || calleeStatus is not { HasRemoteMedia: true } ||
|
||||
((Image)caller.RemoteVideo).Source is not Bitmap || ((Image)callee.RemoteVideo).Source is not Bitmap)
|
||||
{
|
||||
if (errors.Task.IsCompleted) await errors.Task;
|
||||
if (caller.Completion.IsCompleted) await caller.Completion;
|
||||
if (callee.Completion.IsCompleted) await callee.Completion;
|
||||
await Task.Delay(20, timeout.Token);
|
||||
}
|
||||
Assert.Equal(640, ((Bitmap)((Image)caller.RemoteVideo).Source!).PixelSize.Width);
|
||||
Assert.Equal(360, ((Bitmap)((Image)callee.RemoteVideo).Source!).PixelSize.Height);
|
||||
}
|
||||
|
||||
private static WebRtcCallViewModel Configure(Signaling signaling, Media media) => new(signaling, () => media)
|
||||
{ Camera = new("Camera", "camera"), Microphone = new("Mic", "default"), Target = "bob", Room = "General" };
|
||||
|
||||
private static async Task WaitAsync(Func<bool> condition)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
while (!condition()) await Task.Delay(10, timeout.Token);
|
||||
}
|
||||
|
||||
private sealed class Media : IWebRtcMedia
|
||||
{
|
||||
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public Control LocalVideo { get; } = new Border();
|
||||
public Control RemoteVideo { get; } = new Border();
|
||||
public event Action<CallSignal>? Signal;
|
||||
public event Action<WebRtcMediaStatus>? StatusChanged;
|
||||
public Task Completion => _completion.Task;
|
||||
public WebRtcMediaConfiguration? Configuration { get; private set; }
|
||||
public bool Disposed { get; private set; }
|
||||
public bool StartupCancelled { get; private set; }
|
||||
public bool DelayStartup { get; init; }
|
||||
public List<CallSignal> Received { get; } = [];
|
||||
public async Task StartAsync(WebRtcMediaConfiguration configuration, CancellationToken ct)
|
||||
{
|
||||
Configuration = configuration;
|
||||
if (DelayStartup)
|
||||
{
|
||||
try { await Task.Delay(Timeout.Infinite, ct); }
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{ StartupCancelled = true; throw; }
|
||||
}
|
||||
}
|
||||
public Task HandleSignalAsync(CallSignal signal, CancellationToken ct)
|
||||
{ Received.Add(signal); return Task.CompletedTask; }
|
||||
public void Emit(CallSignal signal) => Signal?.Invoke(signal);
|
||||
public void Report(WebRtcMediaStatus status) => StatusChanged?.Invoke(status);
|
||||
public void Fail() => _completion.TrySetException(new IOException("native failure"));
|
||||
public ValueTask DisposeAsync()
|
||||
{ Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
|
||||
private sealed class Signaling(bool relay) : IWebRtcCallSignaling
|
||||
{
|
||||
public event Action<CallSession>? Invitation;
|
||||
public event Action<CallAccepted>? Accepted;
|
||||
public event Action<CallEnded>? Ended;
|
||||
public event Action<Guid, CallSignal>? Signal;
|
||||
public event Action? Interrupted;
|
||||
public CallSession Call { get; } = new(Guid.NewGuid(), "General", "alice", "bob", relay,
|
||||
DateTimeOffset.UtcNow.AddMinutes(1));
|
||||
public List<CallSignal> Sent { get; } = [];
|
||||
public List<Guid> EndedCalls { get; } = [];
|
||||
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) => Task.FromResult(Call);
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("Legacy LAN transport must not be used");
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
|
||||
public Task EndAsync(Guid callId, CancellationToken ct = default)
|
||||
{ EndedCalls.Add(callId); return Task.CompletedTask; }
|
||||
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default)
|
||||
{ Sent.Add(signal); return Task.CompletedTask; }
|
||||
public void Invite() => Invitation?.Invoke(Call);
|
||||
public void Ready(CallSession? session = null, CallIceServer[]? servers = null) =>
|
||||
Accepted?.Invoke(new(session ?? Call, servers ?? Turn));
|
||||
public void Receive(CallSignal signal) => Signal?.Invoke(Call.Id, signal);
|
||||
public void End() => Ended?.Invoke(new(Call.Id, "ended"));
|
||||
public void Disconnect() => Interrupted?.Invoke();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue