// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The protocol end to end, over a transport made of a string. //! //! A WebSocket conversation is a handshake in HTTP followed by binary frames, //! and both halves are written out here as the octets they are. That is the //! only way to check the thing that actually matters — what goes on the wire //! — and it is why the expectations below are byte-exact wherever the frame //! is small enough to read. //! //! There is no socket and no port: zig-http's memory transport is a slice //! going in and a growable buffer coming out, and the HTTP/1.x driver needs //! no scheduling, so the whole suite runs on `Io.failing`. A library that //! reached for I/O it had not been given would fail loudly here. //! //! The client's frames are built by `mask`/`frame` at the bottom of this //! file, which share no code with `src/frame.zig`. A frame writer checked //! against its own reader agrees with itself by construction; these two have //! only RFC 6455 §5.7 in common. const std = @import("std"); const Io = std.Io; const testing = std.testing; const http = @import("http"); const Request = http.server.Request; const Response = http.server.Response; const Handler = http.server.Handler; const ws = @import("websocket"); const wss = @import("websocket_server"); const gpa = testing.allocator; /// The opening handshake of RFC 6455 §1.3, as a client sends it. const handshake_request = "GET /echo HTTP/1.1\r\n" ++ "Host: server.example.com\r\n" ++ "Upgrade: websocket\r\n" ++ "Connection: Upgrade\r\n" ++ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" ++ "Sec-WebSocket-Version: 13\r\n" ++ "\r\n"; /// And what the server must answer, from the same section. The accept token /// is the one the RFC prints. const handshake_response = "HTTP/1.1 101 Switching Protocols\r\n" ++ "Connection: Upgrade\r\n" ++ "Upgrade: websocket\r\n" ++ "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n" ++ "\r\n"; fn exchange(client: []const u8, handler: Handler) ![]u8 { var c: http.transport.memory.Connection = try .init(gpa, client, .{}); defer c.deinit(); var conn = c.connection(); try http.http1.serve(Io.failing, gpa, &conn, handler, .{ .send_date = false, .server_name = null, }); return gpa.dupe(u8, c.written()); } /// Everything after the handshake response, which is where the frames are. fn framesOf(response: []const u8) ![]const u8 { try testing.expect(std.mem.startsWith(u8, response, handshake_response)); return response[handshake_response.len..]; } // -- the handlers the tests use --------------------------------------------- fn echo(req: *Request, res: *Response) anyerror!void { var buffer: [4096]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; while (try conn.receive()) |message| { try conn.send(message.kind, message.data); } } const echo_handler: Handler = .initStateless(echo); /// The same, but with a buffer small enough that the message limit is /// reachable from a test. fn small(req: *Request, res: *Response) anyerror!void { var buffer: [8]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; while (try conn.receive()) |message| { try conn.send(message.kind, message.data); } } fn chat(req: *Request, res: *Response) anyerror!void { var buffer: [4096]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer, .subprotocols = &.{ "chat.v2", "chat.v1" }, }) catch |err| return wss.refuse(res, err); while (try conn.receive()) |message| { try conn.send(message.kind, message.data); } } // -- the handshake ---------------------------------------------------------- test "RFC 6455 1.3: the opening handshake, octet for octet" { const response = try exchange(handshake_request, echo_handler); defer gpa.free(response); // Nothing after it, because the client sent no frames and the stream // ended: §7.1.5's abnormal closure, which has nobody to complain to. try testing.expectEqualStrings(handshake_response, response); } test "a request that is not a handshake is refused without touching anything" { const response = try exchange( "GET /echo HTTP/1.1\r\nHost: a\r\n\r\n", echo_handler, ); defer gpa.free(response); try testing.expect(std.mem.startsWith(u8, response, "HTTP/1.1 426 ")); } test "a version this server does not speak is told which one it does" { // §4.4: the `426` carries `Sec-WebSocket-Version`, which is how a client // that guessed learns what to ask for. const response = try exchange( "GET /echo HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\n" ++ "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" ++ "Sec-WebSocket-Version: 8\r\n\r\n", echo_handler, ); defer gpa.free(response); try testing.expect(std.mem.startsWith(u8, response, "HTTP/1.1 426 ")); try testing.expect(std.mem.indexOf(u8, response, "Sec-WebSocket-Version: 13") != null); } test "a key that is not sixteen octets of base64 is refused" { const response = try exchange( "GET /echo HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\n" ++ "Connection: Upgrade\r\nSec-WebSocket-Key: c2hvcnQ=\r\n" ++ "Sec-WebSocket-Version: 13\r\n\r\n", echo_handler, ); defer gpa.free(response); try testing.expect(std.mem.startsWith(u8, response, "HTTP/1.1 400 ")); } test "a subprotocol is chosen from what the client offered" { const response = try exchange( "GET /chat HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\n" ++ "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" ++ "Sec-WebSocket-Version: 13\r\n" ++ "Sec-WebSocket-Protocol: chat.v1, chat.v3\r\n\r\n", .initStateless(chat), ); defer gpa.free(response); // The server's preference is `chat.v2` first, but the client did not // offer it, and §4.2.2 forbids choosing one that was not offered. try testing.expect(std.mem.indexOf(u8, response, "Sec-WebSocket-Protocol: chat.v1") != null); } test "no subprotocol is sent when none of the client's are known" { const response = try exchange( "GET /chat HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\n" ++ "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" ++ "Sec-WebSocket-Version: 13\r\n" ++ "Sec-WebSocket-Protocol: something.else\r\n\r\n", .initStateless(chat), ); defer gpa.free(response); try testing.expect(std.mem.indexOf(u8, response, "Sec-WebSocket-Protocol") == null); // And the connection still opened, because a client must cope with that. try testing.expect(std.mem.startsWith(u8, response, "HTTP/1.1 101 ")); } test "no Sec-WebSocket-Extensions is ever sent" { // §9.1 forbids answering with an extension the client did not offer; this // library answers with none at all, because agreeing to a framing it does // not implement would corrupt every message after the handshake. const response = try exchange( "GET /echo HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\n" ++ "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" ++ "Sec-WebSocket-Version: 13\r\n" ++ "Sec-WebSocket-Extensions: permessage-deflate\r\n\r\n", echo_handler, ); defer gpa.free(response); try testing.expect(std.mem.startsWith(u8, response, "HTTP/1.1 101 ")); try testing.expect(std.mem.indexOf(u8, response, "Sec-WebSocket-Extensions") == null); } // -- the framing ------------------------------------------------------------ test "a masked text frame comes back unmasked" { // RFC 6455 §5.7's masked "Hello", and the unmasked "Hello" that §5.1 says // a server must answer with: "A server MUST NOT mask any frames that it // sends to the client." const client = handshake_request ++ "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"; const response = try exchange(client, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x81\x05Hello", try framesOf(response)); } test "a fragmented message is reassembled and answered whole" { // §5.7's "Hel" + "lo", masked because a client must mask. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, false, 0x1, "Hel"); try frame(&client, true, 0x0, "lo"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); // One frame back, not two: the server received a message. try testing.expectEqualSlices(u8, "\x81\x05Hello", try framesOf(response)); } test "a ping is answered with a pong carrying the same payload" { // §5.5.2: "Upon receipt of a Ping frame, an endpoint MUST send a Pong // frame in response", and §5.5.3: it "must have identical 'Application // data'". var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x9, "Hello"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x8a\x05Hello", try framesOf(response)); } test "a ping in the middle of a fragmented message does not disturb it" { // §5.5: "Control frames can be interjected in the middle of a fragmented // message." The reassembled message must come out whole, which it will // not if the control payload was written into the same buffer. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, false, 0x1, "Hel"); try frame(&client, true, 0x9, "ping!"); try frame(&client, true, 0x0, "lo"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x8a\x05ping!" ++ "\x81\x05Hello", try framesOf(response)); } test "a pong is ignored" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0xa, "unsolicited"); try frame(&client, true, 0x1, "hi"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x81\x02hi", try framesOf(response)); } test "a binary message stays binary" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x2, "\x00\x01\xfe\xff"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x82\x04\x00\x01\xfe\xff", try framesOf(response)); } test "an empty message is a message" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x1, ""); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x81\x00", try framesOf(response)); } test "a message long enough to need the two-octet length" { const payload: []const u8 = &@as([200]u8, @splat('x')); var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x1, payload); const response = try exchange(client.items, echo_handler); defer gpa.free(response); const got = try framesOf(response); try testing.expectEqualSlices(u8, "\x81\x7e\x00\xc8", got[0..4]); try testing.expectEqualStrings(payload, got[4..]); } // -- the closing handshake -------------------------------------------------- test "a close is echoed and ends the conversation" { // §5.5.1: "If an endpoint receives a Close frame and did not previously // send a Close frame, the endpoint MUST send a Close frame in response. // (When sending a Close frame in response, the endpoint typically echos // the status code it received.)" var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x8, "\x03\xe8" ++ "bye"); // Anything after a Close is not read. try frame(&client, true, 0x1, "ignored"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x88\x02\x03\xe8", try framesOf(response)); } test "a close with no body is echoed as 1000" { // The peer said nothing, which is 1005 — and §7.4.1 forbids putting 1005 // on the wire, so the echo cannot simply repeat it. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x8, ""); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x88\x02\x03\xe8", try framesOf(response)); } test "a close carrying one octet is a protocol error" { // §5.5.1: "If there is a body, the first two bytes of the body MUST be a // 2-byte unsigned integer". One octet is neither a body nor no body. try expectClose(.protocol_error, 0x8, "\x03"); } test "a close carrying a code that may not be sent is a protocol error" { // 1005 and 1006 exist for an application to be told something; a peer // that puts one in a frame is claiming to know what it cannot. try expectClose(.protocol_error, 0x8, "\x03\xed"); try expectClose(.protocol_error, 0x8, "\x03\xee"); // 1004 is reserved, and 2999 was never defined. try expectClose(.protocol_error, 0x8, "\x03\xec"); try expectClose(.protocol_error, 0x8, "\x0b\xb7"); } test "a close whose reason is not UTF-8 is 1007" { try expectClose(.invalid_payload, 0x8, "\x03\xe8\xff\xfe"); } test "a private-use close code is allowed through" { // §7.4.2 leaves 4000-4999 to whoever is using the protocol, so a server // that refused one would be refusing something it has no business // refusing. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x8, "\x0f\xa0"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x88\x02\x0f\xa0", try framesOf(response)); } // -- what the server refuses ------------------------------------------------ /// Sends one frame and expects the connection to be failed with `want`. fn expectClose(want: ws.Code, opcode: u4, payload: []const u8) !void { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, opcode, payload); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try expectCloseCode(want, try framesOf(response)); } /// That the only thing the server sent was a Close frame carrying `want`. /// /// The code is asserted and the reason is not: the reason is this library's /// own words about what the peer did, useful in a log and not something a /// test should pin, and §5.5.1 leaves its content entirely open. fn expectCloseCode(want: ws.Code, got: []const u8) !void { if (got.len < 4 or got[0] != 0x88) { std.debug.print("not a close frame: {x}\n", .{got}); return error.NotAClose; } // Unmasked, because a server never masks, so the length is the low seven // bits and the payload starts at 2. if (got[1] != got.len - 2) { std.debug.print("close frame length {d} but {d} octets follow\n", .{ got[1], got.len - 2 }); return error.WrongLength; } const code: ws.Code = @fromBackingInt(@intCast(std.mem.readInt(u16, got[2..4], .big))); testing.expectEqual(want, code) catch |err| { std.debug.print("reason: \"{s}\"\n", .{got[4..]}); return err; }; } test "an unmasked frame from a client is a protocol error" { // §5.1: "The server MUST close the connection upon receiving a frame that // is not masked." The rule exists because an unmasked frame lets a // browser be used to write chosen bytes into a proxy's stream. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try client.appendSlice(gpa, "\x81\x05Hello"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try expectCloseCode(.protocol_error, try framesOf(response)); } test "a reserved bit is a protocol error" { // No extension was negotiated, so a set RSV bit means the peer believes // something was agreed that was not. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frameRaw(&client, 0xc1, "hi"); // FIN + RSV1 + text const response = try exchange(client.items, echo_handler); defer gpa.free(response); try expectCloseCode(.protocol_error, try framesOf(response)); } test "an opcode nobody has defined is a protocol error" { try expectClose(.protocol_error, 0x3, ""); try expectClose(.protocol_error, 0x7, ""); try expectClose(.protocol_error, 0xb, ""); try expectClose(.protocol_error, 0xf, ""); } test "a fragmented control frame is a protocol error" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frameRaw(&client, 0x09, "x"); // FIN clear on a ping const response = try exchange(client.items, echo_handler); defer gpa.free(response); try expectCloseCode(.protocol_error, try framesOf(response)); } test "a control frame longer than 125 octets is a protocol error" { try expectClose(.protocol_error, 0x9, &@as([126]u8, @splat('x'))); } test "a continuation with nothing to continue is a protocol error" { try expectClose(.protocol_error, 0x0, "orphan"); } test "a new message while one is in progress is a protocol error" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, false, 0x1, "first"); try frame(&client, true, 0x1, "second"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try expectCloseCode(.protocol_error, try framesOf(response)); } test "a text message that is not UTF-8 is 1007" { // §8.1: an endpoint that receives one "MUST _Fail the WebSocket // Connection_". 0xff is not a byte UTF-8 has any use for. try expectClose(.invalid_payload, 0x1, "\xff"); // A truncated sequence: the first octet of a three-byte code point and // then nothing. try expectClose(.invalid_payload, 0x1, "\xe2\x82"); // An overlong encoding of `/`, which is the one that gets past a naive // path check. try expectClose(.invalid_payload, 0x1, "\xc0\xaf"); // A surrogate, which UTF-8 may not encode. try expectClose(.invalid_payload, 0x1, "\xed\xa0\x80"); } test "valid UTF-8 that looks alarming is allowed through" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); // A four-octet code point and an embedded NUL, both perfectly valid. try frame(&client, true, 0x1, "\xf0\x9f\x92\xa9\x00"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x81\x05\xf0\x9f\x92\xa9\x00", try framesOf(response)); } test "a code point split across a fragment boundary is still valid" { // The reason UTF-8 is checked on the assembled message rather than frame // by frame: neither half of this is valid on its own. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, false, 0x1, "\xf0\x9f"); try frame(&client, true, 0x0, "\x92\xa9"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x81\x04\xf0\x9f\x92\xa9", try framesOf(response)); } test "a message larger than the buffer is 1009" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x1, "more than eight octets"); const response = try exchange(client.items, .initStateless(small)); defer gpa.free(response); try expectCloseCode(.message_too_big, try framesOf(response)); } test "fragments that add up to more than the buffer are 1009" { // The limit is on the message, not on the frame, which is the whole // point: a peer that could get past it by fragmenting would have no // limit at all. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, false, 0x1, "12345"); try frame(&client, true, 0x0, "67890"); const response = try exchange(client.items, .initStateless(small)); defer gpa.free(response); try expectCloseCode(.message_too_big, try framesOf(response)); } test "a length said in more octets than it needed is a protocol error" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); // 0x81 0xfe 0x0002 with a mask: two octets said in the sixteen-bit form. try client.appendSlice(gpa, "\x81\xfe\x00\x02\x00\x00\x00\x00hi"); const response = try exchange(client.items, echo_handler); defer gpa.free(response); try expectCloseCode(.protocol_error, try framesOf(response)); } // -- the client's half, written independently ------------------------------- /// One masked frame, as a client sends it. /// /// Shares nothing with `src/frame.zig` on purpose: the two agree only because /// both were written from RFC 6455 §5.2, and a disagreement is a finding /// rather than a coincidence. fn frame(out: *std.ArrayList(u8), fin: bool, opcode: u4, payload: []const u8) !void { const first: u8 = (@as(u8, @intFromBool(fin)) << 7) | opcode; try frameRaw(out, first, payload); } /// The same with the first octet given whole, for the frames a conformant /// client could not send. fn frameRaw(out: *std.ArrayList(u8), first: u8, payload: []const u8) !void { try out.append(gpa, first); // Always masked: §5.3 gives a client no choice. if (payload.len < 126) { try out.append(gpa, 0x80 | @as(u8, @intCast(payload.len))); } else if (payload.len <= 65535) { try out.append(gpa, 0x80 | 126); var len: [2]u8 = undefined; std.mem.writeInt(u16, &len, @intCast(payload.len), .big); try out.appendSlice(gpa, &len); } else { try out.append(gpa, 0x80 | 127); var len: [8]u8 = undefined; std.mem.writeInt(u64, &len, payload.len, .big); try out.appendSlice(gpa, &len); } // A fixed key rather than a random one, so that a failing test prints the // same octets twice running. Unpredictability is a requirement on a real // client and buys a test nothing. const key = [4]u8{ 0x37, 0xfa, 0x21, 0x3d }; try out.appendSlice(gpa, &key); for (payload, 0..) |byte, i| { try out.append(gpa, byte ^ key[i % 4]); } } test "the test client's masking is the one in RFC 6455 5.7" { // The independent writer, checked against the RFC's worked example, so // that every expectation above rests on something the document printed. var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); try frame(&out, true, 0x1, "Hello"); try testing.expectEqualSlices( u8, &.{ 0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58 }, out.items, ); } test "closing twice sends one Close frame" { // A handler that closes and then falls out of its loop into a `defer` // that closes again has done nothing wrong, and §5.5.1 says the second // frame must not go out. var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x1, "go"); const response = try exchange(client.items, .initStateless(closesTwice)); defer gpa.free(response); try testing.expectEqualSlices(u8, "\x88\x02\x03\xe9", try framesOf(response)); } fn closesTwice(req: *Request, res: *Response) anyerror!void { var buffer: [64]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; defer conn.close(.going_away, "again") catch {}; _ = try conn.receive(); try conn.close(.going_away, ""); } test "sending after closing says so, rather than looking like a broken stream" { var client: std.ArrayList(u8) = .empty; defer client.deinit(gpa); try client.appendSlice(gpa, handshake_request); try frame(&client, true, 0x1, "go"); const response = try exchange(client.items, .initStateless(sendsAfterClosing)); defer gpa.free(response); // The Close went out and the message after it did not. try testing.expectEqualSlices(u8, "\x88\x02\x03\xe8", try framesOf(response)); } fn sendsAfterClosing(req: *Request, res: *Response) anyerror!void { var buffer: [64]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; _ = try conn.receive(); try conn.close(.normal, ""); try testing.expectError(error.Closed, conn.sendText("too late")); }