Debian Codegraph @

pkg/base1/test-protocol.ts

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import QUnit from "qunit-tests";
3
4 interface ControlMessage {
5 command: string;
6 problem?: string;
7 [key: string]: unknown;
8 }
9
10 function connect(): Promise<WebSocket> {
11 const ws = new WebSocket(`ws://${window.location.host}/cockpit/socket`, "cockpit1");
12 return new Promise((resolve, reject) => {
13 ws.onopen = () => resolve(ws);
14 ws.onerror = () => reject(new Error("WebSocket connection failed"));
15 });
16 }
17
18 function send_control(ws: WebSocket, message: ControlMessage): void {
19 ws.send("\n" + JSON.stringify(message));
20 }
21
22 function read_control(ws: WebSocket): Promise<ControlMessage> {
23 return new Promise(resolve => {
24 ws.onmessage = event => {
25 const message = event.data as string;
26 const pos = message.indexOf("\n");
27 if (pos < 0)
28 throw new Error("invalid message");
29
30 const channel = message.substring(0, pos);
31 const data = message.substring(pos + 1);
32
33 if (channel === "") {
34 resolve(JSON.parse(data) as ControlMessage);
35 }
36 };
37 });
38 }
39
40 function read_text_data(ws: WebSocket, expected_channel: string): Promise<string> {
41 const prefix = expected_channel + "\n";
42 return new Promise((resolve, reject) => {
43 ws.onmessage = event => {
44 if (typeof event.data !== "string")
45 return reject(new Error("expected text frame, got binary"));
46 if (!event.data.startsWith(prefix))
47 return reject(new Error(`expected channel ${expected_channel}, got: ${event.data}`));
48 resolve(event.data.substring(prefix.length));
49 };
50 });
51 }
52
53 function read_binary_data(ws: WebSocket, expected_channel: string): Promise<Uint8Array> {
54 const prefix = new TextEncoder().encode(expected_channel + "\n");
55 return new Promise((resolve, reject) => {
56 ws.onmessage = event => {
57 if (!(event.data instanceof ArrayBuffer))
58 return reject(new Error("expected binary frame, got text"));
59 const frame = new Uint8Array(event.data);
60 if (frame.length < prefix.length || !prefix.every((b, i) => frame[i] === b))
61 return reject(new Error(`expected channel ${expected_channel}`));
62 resolve(frame.subarray(prefix.length));
63 };
64 });
65 }
66
67 async function init(ws: WebSocket): Promise<string> {
68 const message = await read_control(ws);
69 if (message.command !== "init")
70 throw new Error(`expected init, got ${message.command}`);
71 const seed = message["channel-seed"];
72 if (typeof seed !== "string")
73 throw new Error("missing channel-seed in init message");
74 send_control(ws, { command: "init", version: 1 });
75 return seed;
76 }
77
78 /* Wait for close, returning the last message received */
79 async function wait_close(ws: WebSocket): Promise<ControlMessage> {
80 const close_promise = new Promise(resolve => {
81 ws.onclose = resolve;
82 });
83 const message = await read_control(ws);
84 await close_promise;
85 return message;
86 }
87
88 QUnit.test("first message from host is init", async assert => {
89 const ws = await connect();
90
91 try {
92 const message = await read_control(ws);
93 assert.strictEqual(message.command, "init");
94 assert.strictEqual(message.version, 1);
95 assert.ok("channel-seed" in message);
96 assert.ok("host" in message);
97 assert.ok("csrf-token" in message);
98 } finally {
99 ws.close();
100 }
101 });
102
103 QUnit.test("host must ensure that init is the first message", async assert => {
104 const ws = await connect();
105 await read_control(ws); // skip the init
106
107 // send something first that's not "init"
108 send_control(ws, { command: "ping" });
109
110 // make sure we get shut down
111 const message = await wait_close(ws);
112 assert.equal(message.command, "close");
113 assert.equal(message.problem, "protocol-error");
114 });
115
116 QUnit.test("host tolerates payload message before init", async assert => {
117 const ws = await connect();
118 await read_control(ws); // skip the init
119
120 // send payload message before init — the server should reject this
121 // with a protocol-error (like it does for control messages before
122 // init) but currently it silently ignores it.
123 ws.send("somechannel\npayload");
124
125 // connection should still work
126 send_control(ws, { command: "init", version: 1 });
127 send_control(ws, { command: "ping", still: "alive" });
128 const pong = await read_control(ws);
129 assert.equal(pong.command, "pong");
130 assert.equal(pong.still, "alive");
131
132 ws.close();
133 });
134
135 QUnit.test("server accepts extra init messages", async assert => {
136 /* Old versions of the shell used to accidentally forward the init message
137 * from each iframe to the webserver, and since a new webserver may be used
138 * with old versions of the shell, we need to make sure the webserver
139 * continues to accept multiple init messages without error.
140 */
141 const ws = await connect();
142
143 try {
144 // skip the init
145 const init = await read_control(ws);
146 assert.strictEqual(init.command, "init");
147
148 // we need to send init first
149 send_control(ws, { command: "init", version: 1 });
150
151 // but after that additional init is ignored
152 send_control(ws, { command: "init", version: 1 });
153
154 // send a ping: if we get the pong then we survived the extra inits
155 send_control(ws, { command: "ping", still: "alive" });
156 const pong = await read_control(ws);
157 assert.equal(pong.command, "pong", "got pong");
158 assert.equal(pong.still, "alive", "still alive");
159 } finally {
160 ws.close();
161 }
162 });
163
164 /*
165 * cockpit-ws doesn't check the WebSocket frame type on inbound messages: it
166 * just forwards them blindly to the bridge. The information about if a
167 * message was binary or text is inherently lost in the cockpit protocol, and
168 * the bridge does the correct thing in all cases.
169 *
170 * The following three tests are meant to document the somewhat-broken status
171 * quo. This was never an intentionally-supported feature and should probably
172 * be a hard error. A testcase used to depend on the ability to send text data
173 * to binary channels and has since been fixed. We have no data on if actual
174 * production code is also accidentally relying on this implementation quirk.
175 */
176 QUnit.test("text frame on binary channel: response is binary", async assert => {
177 const ws = await connect();
178 ws.binaryType = "arraybuffer";
179 const channel = await init(ws) + "1";
180
181 send_control(ws, { command: "open", channel, payload: "echo", binary: "raw" });
182
183 const ready = await read_control(ws);
184 assert.equal(ready.command, "ready", "channel ready");
185
186 // send a text frame on a binary channel
187 ws.send(`${channel}\nhello`);
188
189 // make sure it comes back as text
190 const payload = await read_binary_data(ws, channel);
191 assert.equal(new TextDecoder().decode(payload), "hello", "payload survived round-trip");
192
193 ws.close();
194 });
195
196 QUnit.test("binary frame on text channel: response is text", async assert => {
197 const ws = await connect();
198 ws.binaryType = "arraybuffer";
199 const channel = await init(ws) + "1";
200
201 send_control(ws, { command: "open", channel, payload: "echo" });
202
203 const ready = await read_control(ws);
204 assert.equal(ready.command, "ready", "channel ready");
205
206 // send a binary frame on a text channel
207 ws.send(new TextEncoder().encode(`${channel}\nhello`));
208
209 // make sure it comes back as text
210 const payload = await read_text_data(ws, channel);
211 assert.equal(payload, "hello", "payload survived round-trip");
212
213 ws.close();
214 });
215
216 QUnit.test("non-utf8 on text channel is rejected by the bridge", async assert => {
217 /* The bridge runs a strict UTF-8 decoder on text channels. Invalid
218 * bytes cause a protocol-error channel close — the data never reaches
219 * cockpit-ws, which would g_critical() and drop it.
220 */
221 const ws = await connect();
222 ws.binaryType = "arraybuffer";
223 const channel = await init(ws) + "1";
224
225 send_control(ws, { command: "open", channel, payload: "echo" });
226 const ready = await read_control(ws);
227 assert.equal(ready.command, "ready", "channel ready");
228
229 // send invalid UTF-8 bytes via a binary frame on a text channel
230 const header = new TextEncoder().encode(channel + "\n");
231 const garbage = new Uint8Array([0x80, 0xff, 0xfe, 0xc0, 0xc1]);
232 const frame = new Uint8Array(header.length + garbage.length);
233 frame.set(header);
234 frame.set(garbage, header.length);
235 ws.send(frame);
236
237 // the bridge closes the channel with a protocol-error
238 const close = await read_control(ws);
239 assert.equal(close.command, "close", "channel closed");
240 assert.equal(close.channel, channel, "correct channel");
241 assert.equal(close.problem, "protocol-error", "protocol-error due to invalid UTF-8");
242
243 ws.close();
244 });
245
246 QUnit.module("tests that need test-server warnings disabled", hooks => {
247 /*
248 * Some of these tests will trigger cockpit-ws or cockpit-bridge to print out
249 * warnings (on protocol errors, for example). Let the test server know that
250 * before starting the tests, so it doesn't treat those messages as fatal.
251 */
252
253 // hooks wait for the promise to be resolved before continuing
254 hooks.before(async () => { await fetch("/mock/expect-warnings") });
255 hooks.after(async () => { await fetch("/mock/dont-expect-warnings") });
256
257 QUnit.test("host must return an error when 'channel' is not given in 'open'", async assert => {
258 const ws = await connect();
259 await read_control(ws); // skip the init
260
261 send_control(ws, { command: "init", version: 1 });
262
263 // this is broken
264 send_control(ws, { command: "open", payload: "fsread", path: "/etc/passwd" });
265
266 // wait for the shutdown
267 const message = await wait_close(ws);
268 assert.equal(message.command, "close");
269 assert.equal(message.problem, "protocol-error");
270 });
271
272 QUnit.test("host ignores frame without newline", async assert => {
273 const ws = await connect();
274 await read_control(ws); // skip the init
275
276 send_control(ws, { command: "init", version: 1 });
277
278 // send a frame without a newline — this should be a
279 // protocol-error, but currently it's silently ignored.
280 ws.send("no newline here");
281
282 // connection should still work - verify with ping/pong
283 send_control(ws, { command: "ping", test: "still-alive" });
284 const pong = await read_control(ws);
285 assert.equal(pong.command, "pong");
286 assert.equal(pong.test, "still-alive");
287
288 ws.close();
289 });
290
291 QUnit.test("host rejects control message that is not an object (array)", async assert => {
292 const ws = await connect();
293 await read_control(ws); // skip the init
294
295 send_control(ws, { command: "init", version: 1 });
296
297 // send a control message that's an array, not an object
298 ws.send("\n[1, 2, 3]");
299
300 const message = await wait_close(ws);
301 assert.equal(message.command, "close");
302 assert.equal(message.problem, "protocol-error");
303 });
304
305 QUnit.test("host rejects control message that is not an object (null)", async assert => {
306 const ws = await connect();
307 await read_control(ws); // skip the init
308
309 send_control(ws, { command: "init", version: 1 });
310
311 // send a control message that's null
312 ws.send("\nnull");
313
314 const message = await wait_close(ws);
315 assert.equal(message.command, "close");
316 assert.equal(message.problem, "protocol-error");
317 });
318
319 QUnit.test("host rejects control message with invalid JSON", async assert => {
320 const ws = await connect();
321 await read_control(ws); // skip the init
322
323 send_control(ws, { command: "init", version: 1 });
324
325 // send invalid JSON
326 ws.send("\n{not valid json}");
327
328 const message = await wait_close(ws);
329 assert.equal(message.command, "close");
330 assert.equal(message.problem, "protocol-error");
331 });
332
333 QUnit.test("host rejects control message without command", async assert => {
334 const ws = await connect();
335 await read_control(ws); // skip the init
336
337 send_control(ws, { command: "init", version: 1 });
338
339 // send a control message without "command" field
340 ws.send('\n{"channel": "test"}');
341
342 const message = await wait_close(ws);
343 assert.equal(message.command, "close");
344 assert.equal(message.problem, "protocol-error");
345 });
346
347 QUnit.test("host rejects empty control message", async assert => {
348 const ws = await connect();
349 await read_control(ws); // skip the init
350
351 send_control(ws, { command: "init", version: 1 });
352
353 // send an empty object as a control message
354 ws.send("\n{}");
355
356 const message = await wait_close(ws);
357 assert.equal(message.command, "close");
358 assert.equal(message.problem, "protocol-error");
359 });
360 });
361
362 QUnit.start();