-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlSessionTests.cs
More file actions
387 lines (322 loc) · 14.1 KB
/
Copy pathControlSessionTests.cs
File metadata and controls
387 lines (322 loc) · 14.1 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
using System.Text.Json;
using System.Text.Json.Nodes;
using SwitchifyPc.Core.Control;
using SwitchifyPc.Core.Input;
using SwitchifyPc.Core.Pairing;
using SwitchifyPc.Core.Settings;
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);
Assert.True(result.HasAuthenticatedDevice);
Assert.Equal(DeviceId, result.AuthenticatedDeviceId);
Assert.False(result.AuthenticatedDeviceWasPreviouslyUsed);
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 PreservesPreviouslyUsedDeviceMetadataForAuthenticatedCommands()
{
FakeInputAdapter adapter = new();
ControlSession session = CreateSession(adapter, lastSeenAt: Now - 500);
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("keyboard.key", new { key = "Meta" }));
Assert.True(result.HasAuthenticatedDevice);
Assert.Equal(DeviceId, result.AuthenticatedDeviceId);
Assert.True(result.AuthenticatedDeviceWasPreviouslyUsed);
}
[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 AuthenticatedModifierCommandsRouteToExecutor()
{
FakeInputAdapter adapter = new();
ControlSession session = CreateSession(adapter);
ControlSessionResult down = await session.ProcessMessageAsync(SignedCommand("keyboard.modifierDown", new { key = "Ctrl" }));
ControlSessionResult up = await session.ProcessMessageAsync(SignedCommand("keyboard.modifierUp", new { key = "Ctrl" }, id: "request-2"));
Assert.True(down.HasResponse);
Assert.True(up.HasResponse);
Assert.Equal(["setKeyDown:Ctrl:True", "setKeyDown:Ctrl:False"], 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");
Assert.False(unknown.HasAuthenticatedDevice);
Assert.False(invalidAuth.HasAuthenticatedDevice);
}
[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 AuthenticatedRepeatStartExecutesInitialCommandAndStopAcknowledges()
{
FakeInputAdapter adapter = new();
ControlSession session = CreateSession(adapter, mouseRepeatSettings: new FakeMouseRepeatSettings(MouseRepeatSettingsModel.Default));
ControlSessionResult start = await session.ProcessMessageAsync(SignedCommand(
"mouse.repeat.start",
new
{
command = new
{
type = "mouse.move",
payload = new { dx = 4, dy = 5 }
}
}));
ControlSessionResult stop = await session.ProcessMessageAsync(SignedCommand("mouse.repeat.stop", new { }, id: "request-2"));
Assert.True(start.HasResponse);
Assert.True(stop.HasResponse);
Assert.Equal(["moveMouseBy:4,5"], adapter.Calls);
}
[Fact]
public async Task DisconnectingReleasesHeldInputs()
{
FakeInputAdapter adapter = new();
FakeCursorOverlay overlay = new();
ControlSession session = CreateSession(adapter, overlay);
await session.ProcessMessageAsync(SignedCommand("mouse.dragStart", new { button = "left" }, id: "request-1"));
await session.ProcessMessageAsync(SignedCommand("keyboard.modifierDown", new { key = "Ctrl" }, id: "request-2"));
ControlSessionResult result = await session.ProcessMessageAsync(SignedCommand("connection.disconnecting", new { }, id: "request-3"));
Assert.True(result.HasResponse);
Assert.Equal(
[
"setMouseButtonDown:left:True",
"setKeyDown:Ctrl:True",
"setMouseButtonDown:left:False",
"setKeyDown:Ctrl:False"
],
adapter.Calls);
Assert.Equal([true, false], overlay.DragActiveChanges);
Assert.Equal(2, 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,
double? lastSeenAt = null,
IMouseRepeatSettingsStore? mouseRepeatSettings = null)
{
MemoryPairingStore store = new(new PairingState(
DesktopId: "desktop-1",
PairedDevices:
[
new PairedDevice(DeviceId, "Phone", Token, PairedAt: 1, lastSeenAt)
]));
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: TestPointerCapabilities());
DesktopCommandExecutor executor = new(adapter, cursorOverlay);
MouseRepeatController? repeatController = mouseRepeatSettings is null
? null
: new MouseRepeatController(executor, mouseRepeatSettings, (_, cancellationToken) => Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken));
return new ControlSession(
new CommandAuthValidator(store, () => Now),
executor,
new FixedPointerProfileProvider(profile),
repeatController);
}
private static PointerCapabilities TestPointerCapabilities()
{
return new PointerCapabilities(
true,
ProtocolConstants.NoAckControlCommandTypes.ToArray(),
ProtocolConstants.CommandTypes.ToArray(),
new MouseRepeatCapabilities(true, true, 250, 250, 250, 100, 2000));
}
private sealed class FakeMouseRepeatSettings(MouseRepeatSettings settings) : IMouseRepeatSettingsStore
{
public MouseRepeatSettings Load() => settings;
public MouseRepeatSettings Save(MouseRepeatSettings next)
{
settings = MouseRepeatSettingsModel.Normalize(next);
return settings;
}
}
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 SetKeyDownAsync(string key, bool down, CancellationToken cancellationToken = default)
{
Calls.Add($"setKeyDown:{key}:{down}");
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);
}
}
}