// SPDX-FileCopyrightText: © 2026 Tim Culverhouse // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Tests that exercise `Connection` against a real message bus. //! //! Everything here is skipped unless `MONSTAR_DBUS_INTEGRATION=1` is set, so //! `zig build test` still passes on a machine with no bus. The flake's //! `checks..dbus-broker` boots a VM whose session bus is dbus-broker, //! sets the variable, and requires that every test ran rather than skipped. const std = @import("std"); const linux = std.os.linux; const posix = std.posix; const Connection = @import("Connection.zig"); const Encoder = Connection.Encoder; const Message = Connection.Message; const MessageType = Connection.MessageType; /// A name this test owns for as long as one test needs it. Requesting a name /// is how a client becomes reachable by something other than its unique name. const test_name = "dev.rockorager.Monstar.LiveBusTest"; /// Skip unless the caller asked for live-bus tests, then connect. Returning /// `error.SkipZigTest` rather than failing keeps the suite runnable anywhere. fn connect() !Connection { const requested = std.testing.environ.getPosix("MONSTAR_DBUS_INTEGRATION") orelse return error.SkipZigTest; if (!std.mem.eql(u8, requested, "1")) return error.SkipZigTest; return Connection.connectSession( std.testing.io, std.testing.allocator, std.testing.environ, ); } /// Address a member on the bus's own object, which every bus implements. fn busMethod(member: []const u8) Connection.Method { return .{ .destination = "org.freedesktop.DBus", .path = "/org/freedesktop/DBus", .interface = "org.freedesktop.DBus", .member = member, }; } /// Call a bus method whose only argument is a string and whose reply is a /// single `u32`, which covers `RequestName`, `ReleaseName`, and friends. fn callStringToUint32( connection: *Connection, member: []const u8, argument: []const u8, flags: ?u32, ) !u32 { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string(argument); if (flags) |value| try body.uint32(value); var reply = try connection.call( busMethod(member), if (flags == null) "s" else "su", body.bytes(), &.{}, 1000, ); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("u", reply.bodySignature()); var decoder = reply.bodyDecoder(); const result = try decoder.uint32(); try decoder.end(); return result; } /// Take messages until one matches `message_type`, `interface`, and `member`, /// discarding the rest. The bus sends messages of its own — `NameAcquired` /// arrives during `Hello` — so a test cannot assume what it is waiting for is /// the next message to arrive. fn waitForMessage( connection: *Connection, message_type: MessageType, interface: []const u8, member: []const u8, timeout_ms: u32, ) !Message { const started = std.Io.Clock.awake.now(std.testing.io); const timeout_ns: i96 = @as(i96, timeout_ms) * std.time.ns_per_ms; while (true) { while (try connection.nextMessage()) |taken| { var message = taken; if (message.messageType() == message_type and std.mem.eql(u8, message.header.interface orelse "", interface) and std.mem.eql(u8, message.header.member orelse "", member)) return message; message.deinit(); } const elapsed = started.durationTo(std.Io.Clock.awake.now(std.testing.io)).nanoseconds; if (elapsed >= timeout_ns) return error.Timeout; const remaining_ms: i32 = @intCast(@divTrunc( timeout_ns - elapsed + std.time.ns_per_ms - 1, std.time.ns_per_ms, )); var poll_fd = [_]posix.pollfd{.{ .fd = connection.getFd(), .events = posix.POLL.IN, .revents = 0, }}; if (try posix.poll(&poll_fd, remaining_ms) == 0) return error.Timeout; } } test "live bus: connecting authenticates and registers" { // `connectSession` only returns once `Hello` has been answered, so a // connection at all is evidence that authentication and registration // both worked against a real bus. var connection = try connect(); defer connection.deinit(); try std.testing.expect(connection.getFd() >= 0); } /// Accepts a message sent by `sender`. fn isFrom(sender: []const u8, message: *const Message) bool { return std.mem.eql(u8, message.header.sender orelse "", sender); } test "live bus: the unique name is kept and is what peers see as the sender" { // A portal predicts its Request object's path from the caller's unique // name, so the name has to be the one the bus actually stamps on what // this connection sends -- which a signal routed back to itself shows. var connection = try connect(); defer connection.deinit(); const name = connection.uniqueName(); try std.testing.expect(std.mem.startsWith(u8, name, ":")); const interface = "dev.rockorager.Monstar.LiveBusTest.UniqueName"; try connection.addMatch("type='signal',interface='" ++ interface ++ "'"); try connection.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Ping", }, "", &.{}); var signal = try connection.waitForMessage(name, isFrom, 5000); defer signal.deinit(); try std.testing.expectEqualStrings(interface, signal.header.interface.?); } test "live bus: GetId returns the bus identifier" { var connection = try connect(); defer connection.deinit(); var reply = try connection.call(busMethod("GetId"), "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("s", reply.bodySignature()); var decoder = reply.bodyDecoder(); const id = try decoder.string(); // The specification fixes the bus id at 32 hexadecimal characters. try std.testing.expectEqual(@as(usize, 32), id.len); for (id) |c| try std.testing.expect(std.ascii.isHex(c)); try decoder.end(); } test "live bus: the system bus is reached and answers" { const requested = std.testing.environ.getPosix("MONSTAR_DBUS_INTEGRATION") orelse return error.SkipZigTest; if (!std.mem.eql(u8, requested, "1")) return error.SkipZigTest; // A different bus from the session's: its own socket, its own id. var system = try Connection.connectSystem(std.testing.io, std.testing.allocator, std.testing.environ); defer system.deinit(); var session = try connect(); defer session.deinit(); var ids: [2][32]u8 = undefined; for ([_]*Connection{ &system, &session }, &ids) |connection, *id| { var reply = try connection.call(busMethod("GetId"), "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); var decoder = reply.bodyDecoder(); const got = try decoder.string(); try std.testing.expectEqual(@as(usize, 32), got.len); id.* = got[0..32].*; } try std.testing.expect(!std.mem.eql(u8, &ids[0], &ids[1])); } test "live bus: ListNames includes the bus itself" { var connection = try connect(); defer connection.deinit(); var reply = try connection.call(busMethod("ListNames"), "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("as", reply.bodySignature()); var decoder = reply.bodyDecoder(); const end = try decoder.beginArray('s'); var found_bus = false; var count: usize = 0; while (!try decoder.arrayFinished(end)) { const name = try decoder.string(); if (std.mem.eql(u8, name, "org.freedesktop.DBus")) found_bus = true; count += 1; } try decoder.endArray(end); try decoder.end(); try std.testing.expect(found_bus); // Our own unique name is on the bus too, so there is more than one. try std.testing.expect(count >= 2); } test "live bus: Introspect returns a body larger than one read" { // The bus object's introspection XML is several kilobytes, which makes it // the cheapest way to check that a body spanning more than one `recvmsg` // is reassembled correctly. var connection = try connect(); defer connection.deinit(); var reply = try connection.call(.{ .destination = "org.freedesktop.DBus", .path = "/org/freedesktop/DBus", .interface = "org.freedesktop.DBus.Introspectable", .member = "Introspect", }, "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); var decoder = reply.bodyDecoder(); const xml = try decoder.string(); try decoder.end(); try std.testing.expect(xml.len > 1024); try std.testing.expect(std.mem.find(u8, xml, "org.freedesktop.DBus") != null); } test "live bus: a requested name is owned, resolvable, and released" { var connection = try connect(); defer connection.deinit(); // 4 is DO_NOT_QUEUE: fail outright rather than wait if someone else has it. const request_result = try callStringToUint32(&connection, "RequestName", test_name, 4); // 1 is PRIMARY_OWNER. try std.testing.expectEqual(@as(u32, 1), request_result); { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string(test_name); var reply = try connection.call(busMethod("NameHasOwner"), "s", body.bytes(), &.{}, 1000); defer reply.deinit(); try std.testing.expectEqualStrings("b", reply.bodySignature()); var decoder = reply.bodyDecoder(); try std.testing.expect(try decoder.boolean()); try decoder.end(); } { // The owner of the name we just took is our own connection, so the // bus should agree that it belongs to this process. var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string(test_name); var owner_reply = try connection.call(busMethod("GetNameOwner"), "s", body.bytes(), &.{}, 1000); defer owner_reply.deinit(); try std.testing.expectEqualStrings("s", owner_reply.bodySignature()); var owner_decoder = owner_reply.bodyDecoder(); const unique_name = try owner_decoder.string(); try owner_decoder.end(); try std.testing.expect(unique_name.len > 1); try std.testing.expectEqual(@as(u8, ':'), unique_name[0]); const pid = try callStringToUint32( &connection, "GetConnectionUnixProcessID", unique_name, null, ); try std.testing.expectEqual(@as(u32, @intCast(linux.getpid())), pid); } // 1 is RELEASED. const release_result = try callStringToUint32(&connection, "ReleaseName", test_name, null); try std.testing.expectEqual(@as(u32, 1), release_result); } test "live bus: a matched signal is routed back to its sender" { var connection = try connect(); defer connection.deinit(); const interface = "dev.rockorager.Monstar.LiveBusTest"; try connection.addMatch("type='signal',interface='" ++ interface ++ "'"); var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.uint32(0xfeedface); try body.string("hello from the test"); try connection.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Ping", }, "us", body.bytes()); var signal = try waitForMessage(&connection, .signal, interface, "Ping", 5000); defer signal.deinit(); try std.testing.expectEqualStrings("/dev/rockorager/Monstar/LiveBusTest", signal.header.path.?); try std.testing.expectEqualStrings("us", signal.bodySignature()); var decoder = signal.bodyDecoder(); try std.testing.expectEqual(@as(u32, 0xfeedface), try decoder.uint32()); try std.testing.expectEqualStrings("hello from the test", try decoder.string()); try decoder.end(); } test "live bus: a signal with a destination reaches that peer alone" { // A portal answers a request with a signal addressed to the caller. // The recipient installs no match rule and still receives it; a third // connection whose match rule accepts the signal does not, which a // broadcast sent afterwards shows: one sender's messages arrive in // order, so a bystander that sees the broadcast first never saw the // addressed one. var sender = try connect(); defer sender.deinit(); var recipient = try connect(); defer recipient.deinit(); var bystander = try connect(); defer bystander.deinit(); const interface = "dev.rockorager.Monstar.LiveBusTest.Unicast"; try bystander.addMatch("type='signal',interface='" ++ interface ++ "'"); var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.uint32(0); try sender.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Response", .destination = recipient.uniqueName(), }, "u", body.bytes()); try sender.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Broadcast", }, "", &.{}); var response = try waitForMessage(&recipient, .signal, interface, "Response", 5000); defer response.deinit(); try std.testing.expectEqualStrings(recipient.uniqueName(), response.header.destination.?); try std.testing.expectEqualStrings(sender.uniqueName(), response.header.sender.?); while (true) { var message = try bystander.waitForMessage({}, isAnySignal, 5000); defer message.deinit(); if (!std.mem.eql(u8, message.header.interface orelse "", interface)) continue; try std.testing.expectEqualStrings("Broadcast", message.header.member.?); break; } } /// Accepts any signal. fn isAnySignal(_: void, message: *const Message) bool { return message.messageType() == .signal; } test "live bus: calling a name nobody owns yields an error reply" { var connection = try connect(); defer connection.deinit(); const serial = try connection.sendMethod(.{ .destination = "dev.rockorager.Monstar.Nonexistent", .path = "/dev/rockorager/Monstar", .interface = "dev.rockorager.Monstar", .member = "DoesNotMatter", }, "", &.{}, &.{}); var reply = try connection.waitForReply(serial, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.error_reply, reply.messageType()); try std.testing.expectEqual(serial, reply.header.reply_serial.?); try std.testing.expectEqualStrings( "org.freedesktop.DBus.Error.ServiceUnknown", reply.header.error_name.?, ); } test "live bus: replies are correlated with their own calls" { // Several calls are put in flight before any reply is read, then awaited // out of order. Each `waitForReply` must pick out its own serial and leave // the others queued rather than returning whichever reply arrived first. var connection = try connect(); defer connection.deinit(); var serials: [4]u32 = undefined; for (&serials) |*serial| { serial.* = try connection.sendMethod(busMethod("GetId"), "", &.{}, &.{}); } var index: usize = serials.len; while (index > 0) { index -= 1; var reply = try connection.waitForReply(serials[index], 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqual(serials[index], reply.header.reply_serial.?); } } test "live bus: a Unix fd survives the round trip to the bus" { // The bus rejects the call because nothing owns the destination, but it // only gets that far by accepting the descriptor first, which is what the // `unix_fd_passing` negotiation during authentication is for. var connection = try connect(); defer connection.deinit(); try std.testing.expect(connection.unix_fd_enabled); const rc = linux.openat( linux.AT.FDCWD, "/dev/null", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0, ); if (linux.errno(rc) != .SUCCESS) return error.OpenFailed; const fd: posix.fd_t = @intCast(rc); defer _ = linux.close(fd); var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.unixFd(0); var reply = try connection.call(.{ .destination = "dev.rockorager.Monstar.Nonexistent", .path = "/dev/rockorager/Monstar", .interface = "dev.rockorager.Monstar", .member = "TakeFd", }, "h", body.bytes(), &.{fd}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.error_reply, reply.messageType()); } test "live bus: a descriptor passes from one client to another" { // The bus does not copy a descriptor through the message body; it moves // the open file itself with `SCM_RIGHTS`, so what the receiver gets is a // different descriptor number onto the same file. Two connections and a // pipe are enough to show that end to end: the sender keeps the write end, // the receiver is handed the read end, and what comes out of it is what // was written in. var receiver = try connect(); defer receiver.deinit(); var sender = try connect(); defer sender.deinit(); const service = "dev.rockorager.Monstar.LiveBusTest.FdReceiver"; // 4 is DO_NOT_QUEUE, so a name left behind by an earlier run fails here // rather than making this test wait for it. try std.testing.expectEqual( @as(u32, 1), try callStringToUint32(&receiver, "RequestName", service, 4), ); defer _ = callStringToUint32(&receiver, "ReleaseName", service, null) catch {}; var pipe_fds: [2]posix.fd_t = undefined; if (linux.errno(linux.pipe2(&pipe_fds, .{ .CLOEXEC = true })) != .SUCCESS) return error.PipeFailed; const read_end = pipe_fds[0]; const write_end = pipe_fds[1]; defer _ = linux.close(write_end); // The read end is sent, which does not close it here, so this side still // owns its copy and has to let it go. defer _ = linux.close(read_end); const secret = "a descriptor crossed the bus"; const written = linux.write(write_end, secret, secret.len); if (linux.errno(written) != .SUCCESS or written != secret.len) return error.WriteFailed; var body: Encoder = .init(std.testing.allocator); defer body.deinit(); // The body carries an index into the descriptor array, not the descriptor. try body.unixFd(0); const serial = try sender.sendMethod(.{ .destination = service, .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = "dev.rockorager.Monstar.LiveBusTest", .member = "TakeFd", }, "h", body.bytes(), &.{read_end}); var call = try waitForMessage( &receiver, .method_call, "dev.rockorager.Monstar.LiveBusTest", "TakeFd", 5000, ); defer call.deinit(); try std.testing.expectEqualStrings("h", call.bodySignature()); try std.testing.expectEqual(@as(u32, 1), call.header.unix_fd_count); try std.testing.expectEqual(@as(usize, 1), call.fds.len); var decoder = call.bodyDecoder(); const index = try decoder.unixFd(); try decoder.end(); try std.testing.expectEqual(@as(u32, 0), index); const received = call.fds[index]; // A distinct number is the evidence that this arrived as ancillary data // rather than as a number copied through the body. try std.testing.expect(received != read_end); var buffer: [secret.len]u8 = undefined; const count = linux.read(received, &buffer, buffer.len); if (linux.errno(count) != .SUCCESS) return error.ReadFailed; try std.testing.expectEqual(secret.len, count); try std.testing.expectEqualStrings(secret, &buffer); // Answering closes the loop: the bus can only route this back because the // call carried a sender for the reply to be addressed to. try std.testing.expect(!call.noReplyExpected()); try std.testing.expect(call.header.sender != null); try std.testing.expectEqual(@as(u8, ':'), call.header.sender.?[0]); var reply_body: Encoder = .init(std.testing.allocator); defer reply_body.deinit(); try reply_body.uint32(@intCast(count)); try receiver.sendReply(&call, "u", reply_body.bytes(), &.{}); var reply = try sender.waitForReply(serial, 5000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqual(serial, reply.header.reply_serial.?); var reply_decoder = reply.bodyDecoder(); try std.testing.expectEqual(@as(u32, secret.len), try reply_decoder.uint32()); try reply_decoder.end(); } test "live bus: a client answers a call with an error" { // The error path is routed the same way as a return, but the caller gets // the name and the description back rather than a value, which is what // makes a failure on the far side distinguishable from a broken bus. var receiver = try connect(); defer receiver.deinit(); var sender = try connect(); defer sender.deinit(); const service = "dev.rockorager.Monstar.LiveBusTest.Failing"; try std.testing.expectEqual( @as(u32, 1), try callStringToUint32(&receiver, "RequestName", service, 4), ); defer _ = callStringToUint32(&receiver, "ReleaseName", service, null) catch {}; const serial = try sender.sendMethod(.{ .destination = service, .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = "dev.rockorager.Monstar.LiveBusTest", .member = "Fail", }, "", &.{}, &.{}); var call = try waitForMessage( &receiver, .method_call, "dev.rockorager.Monstar.LiveBusTest", "Fail", 5000, ); defer call.deinit(); const error_name = "dev.rockorager.Monstar.LiveBusTest.Error.Refused"; try receiver.sendError(&call, error_name, "refused on purpose"); var reply = try sender.waitForReply(serial, 5000); defer reply.deinit(); try std.testing.expectEqual(MessageType.error_reply, reply.messageType()); try std.testing.expectEqual(serial, reply.header.reply_serial.?); try std.testing.expectEqualStrings(error_name, reply.header.error_name.?); try std.testing.expectEqualStrings("s", reply.bodySignature()); var reply_decoder = reply.bodyDecoder(); try std.testing.expectEqualStrings("refused on purpose", try reply_decoder.string()); try reply_decoder.end(); } test "live bus: a dictionary of variants decodes to the last byte" { // `GetConnectionCredentials` answers with `a{sv}`, the most nested shape // the bus itself will produce. Walking it to the end is what proves the // array, dict-entry, and variant decoding agree with a real encoder. // Recent buses put a `ProcessFD` pidfd in that dictionary, so the reply may // also carry a descriptor; how many it carries is checked against the // header rather than pinned to a number, since that varies by bus version. var connection = try connect(); defer connection.deinit(); var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string("org.freedesktop.DBus"); var reply = try connection.call( busMethod("GetConnectionCredentials"), "s", body.bytes(), &.{}, 1000, ); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("a{sv}", reply.bodySignature()); try std.testing.expectEqual(reply.header.unix_fd_count, @as(u32, @intCast(reply.fds.len))); // Walk the dictionary with the variant skipper so the whole body is // consumed, which is what proves the nested decoding lines up. var decoder = reply.bodyDecoder(); const end = try decoder.beginArray('{'); var entries: usize = 0; while (!try decoder.arrayFinished(end)) { try decoder.structAlignment(); _ = try decoder.string(); const variant_signature = try decoder.variantSignature(); try decoder.skipSignatureValue(variant_signature); entries += 1; } try decoder.endArray(end); try decoder.end(); try std.testing.expect(entries >= 1); }