-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlSessionTests.cs
More file actions
292 lines (241 loc) · 10.4 KB
/
Copy pathControlSessionTests.cs
File metadata and controls
292 lines (241 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using System.Text.Json;
using System.Text.Json.Nodes;
using SwitchifyPc.Core.Control;
using SwitchifyPc.Core.Input;
using SwitchifyPc.Core.Pairing;
using SwitchifyPc.Protocol;
namespace SwitchifyPc.Tests;
public sealed class ControlSessionTests
{
private const string DeviceId = "android-1";
private const string Token = "shared-token";
private const double Now = 1_000_000;
[Fact]
public async Task AuthenticatesAndRoutesCommandToExecutor()
{
FakeInputAdapter adapter = new();
ControlSession session = CreateSession(adapter);
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("keyboard.key", new { key = "Meta" }));
Assert.True(result.HasResponse);
using JsonDocument response = JsonDocument.Parse(result.ResponseJson!);
Assert.Equal("ack", response.RootElement.GetProperty("type").GetString());
Assert.Equal(["pressKey:Meta"], adapter.Calls);
}
[Fact]
public async Task SuppressesResponseForNoAckCommands()
{
FakeInputAdapter adapter = new();
ControlSession session = CreateSession(adapter);
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("mouse.move", new { dx = 10, dy = -2 }, responseMode: "none"));
Assert.False(result.HasResponse);
Assert.Equal(["moveMouseBy:10,-2"], adapter.Calls);
}
[Fact]
public async Task RejectsInvalidJsonAndMalformedPayloads()
{
ControlSession session = CreateSession(new FakeInputAdapter());
ControlSessionResult invalidJson = await session.ProcessMessageAsync("{");
ControlSessionResult invalidPayload = await session.ProcessMessageAsync(SignedCommand("keyboard.key", new { key = "Win" }, signBeforeMutation: true));
AssertError(invalidJson, null, "invalid_json");
AssertError(invalidPayload, "request-1", "invalid_payload");
}
[Fact]
public async Task RejectsUnknownDevicesAndInvalidAuth()
{
ControlSession session = CreateSession(new FakeInputAdapter());
ControlSessionResult unknown = await session.ProcessMessageAsync(SignedCommand("keyboard.key", new { key = "Meta" }, deviceId: "unknown"));
ControlSessionResult invalidAuth = await session.ProcessMessageAsync(SignedCommand("keyboard.key", new { key = "Meta" }, authOverride: "bad-proof"));
AssertError(unknown, "request-1", "unknown_device");
AssertError(invalidAuth, "request-1", "invalid_auth");
}
[Fact]
public async Task ReturnsPointerProfileResponse()
{
ControlSession session = CreateSession(new FakeInputAdapter());
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("pointer.profile", new { }));
Assert.True(result.HasResponse);
using JsonDocument response = JsonDocument.Parse(result.ResponseJson!);
Assert.Equal("pointer.profile", response.RootElement.GetProperty("type").GetString());
JsonElement payload = response.RootElement.GetProperty("payload");
Assert.Equal("display-1", payload.GetProperty("displayId").GetString());
Assert.True(ProtocolValidator.ValidateProtocolResponse(response.RootElement).Ok);
}
[Fact]
public async Task DisconnectingReleasesHeldMouseButtons()
{
FakeInputAdapter adapter = new();
FakeCursorOverlay overlay = new();
ControlSession session = CreateSession(adapter, overlay);
await session.ProcessMessageAsync(SignedCommand("mouse.dragStart", new { button = "left" }, id: "request-1"));
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("connection.disconnecting", new { }, id: "request-2"));
Assert.True(result.HasResponse);
Assert.Equal(
[
"setMouseButtonDown:left:True",
"setMouseButtonDown:left:False"
],
adapter.Calls);
Assert.Equal([true, false], overlay.DragActiveChanges);
Assert.Equal(1, overlay.HideCount);
Assert.Equal(1, overlay.EndSessionCount);
}
[Fact]
public async Task ConvertsExecutorFailuresToProtocolErrors()
{
FakeInputAdapter adapter = new() { ThrowOnPressKey = true };
ControlSession session = CreateSession(adapter);
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("keyboard.key", new { key = "Meta" }));
AssertError(result, "request-1", "adapter_failure");
}
private static ControlSession CreateSession(FakeInputAdapter adapter, ICursorOverlayNotifier? cursorOverlay = null)
{
MemoryPairingStore store = new(new PairingState(
DesktopId: "desktop-1",
PairedDevices:
[
new PairedDevice(DeviceId, "Phone", Token, PairedAt: 1, LastSeenAt: null)
]));
PointerMovementProfile profile = new(
DisplayId: "display-1",
ScaleFactor: 1,
Bounds: new Bounds(0, 0, 1920, 1080),
MaxDelta: ProtocolConstants.MaxPointerDelta,
RecommendedDeltas: new RecommendedDeltas(49, 130, 281),
Capabilities: new PointerCapabilities(true, ProtocolConstants.NoAckControlCommandTypes.ToArray(), ProtocolConstants.CommandTypes.ToArray()));
return new ControlSession(
new CommandAuthValidator(store, () => Now),
new DesktopCommandExecutor(adapter, cursorOverlay),
new FixedPointerProfileProvider(profile));
}
private static string SignedCommand(
string type,
object payload,
string id = "request-1",
string deviceId = DeviceId,
string? responseMode = null,
string? authOverride = null,
bool signBeforeMutation = false)
{
JsonObject command = new()
{
["version"] = ProtocolConstants.ProtocolVersion,
["id"] = id,
["deviceId"] = deviceId,
["timestamp"] = Now,
["type"] = type,
["payload"] = JsonSerializer.SerializeToNode(payload),
["auth"] = ""
};
if (responseMode is not null)
{
command["responseMode"] = responseMode;
}
using JsonDocument unsignedDocument = JsonDocument.Parse(command.ToJsonString());
command["auth"] = authOverride ?? CommandAuth.CreateCommandAuthProof(unsignedDocument.RootElement, Token);
if (signBeforeMutation)
{
command["payload"] = JsonSerializer.SerializeToNode(payload);
}
return command.ToJsonString();
}
private static void AssertError(ControlSessionResult result, string? id, string code)
{
Assert.True(result.HasResponse);
using JsonDocument response = JsonDocument.Parse(result.ResponseJson!);
Assert.Equal("error", response.RootElement.GetProperty("type").GetString());
if (id is null)
{
Assert.Equal(JsonValueKind.Null, response.RootElement.GetProperty("id").ValueKind);
}
else
{
Assert.Equal(id, response.RootElement.GetProperty("id").GetString());
}
Assert.Equal(code, response.RootElement.GetProperty("error").GetProperty("code").GetString());
}
private sealed class FakeInputAdapter : IDesktopInputAdapter
{
public List<string> Calls { get; } = [];
public bool ThrowOnPressKey { get; init; }
public Task MoveMouseByAsync(double dx, double dy, CancellationToken cancellationToken = default)
{
Calls.Add($"moveMouseBy:{dx},{dy}");
return Task.CompletedTask;
}
public Task SetMouseButtonDownAsync(string button, bool down, CancellationToken cancellationToken = default)
{
Calls.Add($"setMouseButtonDown:{button}:{down}");
return Task.CompletedTask;
}
public Task ClickMouseAsync(string button, CancellationToken cancellationToken = default)
{
Calls.Add($"clickMouse:{button}");
return Task.CompletedTask;
}
public Task DoubleClickMouseAsync(string button, CancellationToken cancellationToken = default)
{
Calls.Add($"doubleClickMouse:{button}");
return Task.CompletedTask;
}
public Task ScrollMouseAsync(double dx, double dy, CancellationToken cancellationToken = default)
{
Calls.Add($"scrollMouse:{dx},{dy}");
return Task.CompletedTask;
}
public Task PressKeyAsync(string key, CancellationToken cancellationToken = default)
{
if (ThrowOnPressKey) throw new DesktopInputException("adapter_failure", "Key failed.");
Calls.Add($"pressKey:{key}");
return Task.CompletedTask;
}
public Task PressShortcutAsync(IReadOnlyList<string> keys, CancellationToken cancellationToken = default)
{
Calls.Add($"pressShortcut:{string.Join("+", keys)}");
return Task.CompletedTask;
}
public Task TypeTextAsync(string text, CancellationToken cancellationToken = default)
{
Calls.Add($"typeText:{text}");
return Task.CompletedTask;
}
public Task TypeCharacterAsync(string text, CancellationToken cancellationToken = default)
{
Calls.Add($"typeCharacter:{text}");
return Task.CompletedTask;
}
public Task MediaControlAsync(string action, CancellationToken cancellationToken = default)
{
Calls.Add($"mediaControl:{action}");
return Task.CompletedTask;
}
public Task ControlWindowAsync(string action, CancellationToken cancellationToken = default)
{
Calls.Add($"controlWindow:{action}");
return Task.CompletedTask;
}
}
private sealed class FakeCursorOverlay : ICursorOverlayNotifier
{
public List<bool> DragActiveChanges { get; } = [];
public int HideCount { get; private set; }
public int EndSessionCount { get; private set; }
public void Show(string eventName)
{
}
public void Hide()
{
HideCount += 1;
}
public void EndControlSession()
{
EndSessionCount += 1;
}
public void MarkControlActive()
{
}
public void SetDragActive(bool active)
{
DragActiveChanges.Add(active);
}
}
}