// SPDX-FileCopyrightText: © 2024 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Tests for the wire format and for a whole message crossing a socket. //! //! Everything here runs against `testing.FakeJournal` rather than the //! machine's own journal, so the suite passes on a host with no systemd and //! inside a Nix build sandbox. What it cannot cover -- that journald itself //! accepts and indexes what is sent -- is covered by the NixOS virtual //! machine check in `tests/nixos`. const std = @import("std"); const testing = std.testing; const Allocator = std.mem.Allocator; const Logger = @import("Logger.zig"); const Message = @import("Message.zig"); const constants = @import("constants.zig"); const Facility = constants.Facility; const Priority = constants.Priority; const helper = @import("testing.zig"); const linux = std.os.linux; const F = linux.F; /// A `FakeJournal` and a `Logger` pointed at it, in a directory that goes /// away with the test. const Fixture = struct { tmp: testing.TmpDir, path_buf: [64]u8, journal: helper.FakeJournal, logger: Logger, fn init(self: *Fixture, identifier: ?[]const u8, facility: ?Facility) !void { self.tmp = testing.tmpDir(.{}); errdefer self.tmp.cleanup(); // A relative path, deliberately: `sun_path` is 108 bytes and the // absolute path of a cache directory is not guaranteed to fit. const path = try std.fmt.bufPrint( &self.path_buf, ".zig-cache/tmp/{s}/journal.sock", .{self.tmp.sub_path}, ); self.journal = try .init(path); errdefer self.journal.deinit(); self.logger = try .initPath(testing.io, identifier, facility, path); } fn deinit(self: *Fixture) void { self.logger.deinit(); self.journal.deinit(); self.tmp.cleanup(); } }; /// The raw bytes a single field encodes to, with nothing else in the message. fn encodeOne(allocator: Allocator, logger: *const Logger, key: []const u8, value: []const u8) ![]const u8 { const msg: Message = try .init(logger); defer msg.cancel(); var buf: [256]u8 = undefined; var w = msg.writer(&buf); try w.writeAll(key, value); try w.flush(); return helper.readAll(allocator, msg.memfd); } test "a field is its name, a newline, a little endian u64 length, the value and a newline" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const payload = try encodeOne(testing.allocator, &fixture.logger, "MESSAGE", "hello"); defer testing.allocator.free(payload); try testing.expectEqualSlices( u8, "MESSAGE\n" ++ [_]u8{ 5, 0, 0, 0, 0, 0, 0, 0 } ++ "hello\n", payload, ); } test "the length is a byte count, so a value holding newlines and NULs survives" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const value = "one\ntwo\x00three\n"; const payload = try encodeOne(testing.allocator, &fixture.logger, "MESSAGE", value); defer testing.allocator.free(payload); try testing.expectEqualSlices( u8, "MESSAGE\n" ++ [_]u8{ 14, 0, 0, 0, 0, 0, 0, 0 } ++ value ++ "\n", payload, ); } test "print formats the value and counts its bytes" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const msg: Message = try .init(&fixture.logger); defer msg.cancel(); var buf: [256]u8 = undefined; var w = msg.writer(&buf); try w.print("COUNT", "{d} of {d}", .{ 7, 100 }); try w.flush(); const payload = try helper.readAll(testing.allocator, msg.memfd); defer testing.allocator.free(payload); try testing.expectEqualSlices( u8, "COUNT\n" ++ [_]u8{ 8, 0, 0, 0, 0, 0, 0, 0 } ++ "7 of 100\n", payload, ); } test "a value larger than the writer's buffer is not truncated or reordered" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const big = "x" ** 10_000; const msg: Message = try .init(&fixture.logger); defer msg.cancel(); // Deliberately far smaller than the value, so the write has to drain // through the buffer many times. var buf: [64]u8 = undefined; var w = msg.writer(&buf); try w.writeAll("MESSAGE", big); try w.writeAll("AFTER", "tail"); try w.flush(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); try testing.expectEqual(@as(usize, 2), fields.len); try testing.expectEqualStrings("MESSAGE", fields[0].key); try testing.expectEqualStrings(big, fields[0].value); try testing.expectEqualStrings("AFTER", fields[1].key); try testing.expectEqualStrings("tail", fields[1].value); } test "an unbuffered writer writes straight through" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const msg: Message = try .init(&fixture.logger); defer msg.cancel(); var w = msg.writer(&.{}); try w.writeAll("MESSAGE", "unbuffered"); try w.flush(); const payload = try helper.readAll(testing.allocator, msg.memfd); defer testing.allocator.free(payload); try testing.expectEqualSlices( u8, "MESSAGE\n" ++ [_]u8{ 10, 0, 0, 0, 0, 0, 0, 0 } ++ "unbuffered\n", payload, ); } test "writeSrc records where the message was logged" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const msg: Message = try .init(&fixture.logger); defer msg.cancel(); var buf: [512]u8 = undefined; var w = msg.writer(&buf); const src = @src(); try w.writeSrc(src); try w.flush(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); const entry: helper.Entry = .{ .arena = .init(testing.allocator), .fields = fields, .seals = 0 }; try testing.expectEqualStrings(src.file, entry.get("CODE_FILE").?); try testing.expectEqualStrings(src.fn_name, entry.get("CODE_FUNC").?); var line_buf: [16]u8 = undefined; try testing.expectEqualStrings( try std.fmt.bufPrint(&line_buf, "{d}", .{src.line}), entry.get("CODE_LINE").?, ); } test "the logger's identifier, facility and priority lead the message" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .DAEMON); defer fixture.deinit(); const msg = try fixture.logger.message(.WARNING); defer msg.cancel(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); try testing.expectEqual(@as(usize, 3), fields.len); try testing.expectEqualStrings("SYSLOG_IDENTIFIER", fields[0].key); try testing.expectEqualStrings("journalz-test", fields[0].value); try testing.expectEqualStrings("SYSLOG_FACILITY", fields[1].key); try testing.expectEqualStrings("3", fields[1].value); try testing.expectEqualStrings("PRIORITY", fields[2].key); try testing.expectEqualStrings("4", fields[2].value); } test "a logger with no identifier or facility writes neither field" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const msg = try fixture.logger.message(.INFO); defer msg.cancel(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); try testing.expectEqual(@as(usize, 1), fields.len); try testing.expectEqualStrings("PRIORITY", fields[0].key); } test "a sent message arrives over the socket with its fields intact" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .USER); defer fixture.deinit(); const msg = try fixture.logger.message(.INFO); errdefer msg.cancel(); var buf: [512]u8 = undefined; var w = msg.writer(&buf); try w.writeAll("MESSAGE", "over the wire"); try w.print("ANSWER", "{d}", .{42}); try w.flush(); try msg.send(); var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit(); try testing.expectEqualStrings("journalz-test", entry.get("SYSLOG_IDENTIFIER").?); try testing.expectEqualStrings("1", entry.get("SYSLOG_FACILITY").?); try testing.expectEqualStrings("6", entry.get("PRIORITY").?); try testing.expectEqualStrings("over the wire", entry.get("MESSAGE").?); try testing.expectEqualStrings("42", entry.get("ANSWER").?); } test "the payload is sealed against writing before it is handed over" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .USER); defer fixture.deinit(); fixture.logger.info("sealed", .{}); var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit(); // journald trusts the payload it is given; these are what stop the // sender changing it afterwards. for ([_]u32{ F.SEAL_SEAL, F.SEAL_SHRINK, F.SEAL_GROW, F.SEAL_WRITE, F.SEAL_FUTURE_WRITE, }) |seal| { try testing.expect(entry.seals & seal != 0); } } test "each convenience method sends its own priority" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .USER); defer fixture.deinit(); fixture.logger.err("an error", .{}); fixture.logger.warn("a warning", .{}); fixture.logger.info("a notice", .{}); fixture.logger.debug("a debug", .{}); const expected = [_]struct { priority: []const u8, message: []const u8 }{ .{ .priority = "3", .message = "an error" }, .{ .priority = "4", .message = "a warning" }, .{ .priority = "6", .message = "a notice" }, .{ .priority = "7", .message = "a debug" }, }; // A datagram socket preserves order, so these arrive as they were sent. for (expected) |want| { var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit(); try testing.expectEqualStrings(want.priority, entry.get("PRIORITY").?); try testing.expectEqualStrings(want.message, entry.get("MESSAGE").?); } } test "arguments are formatted into the MESSAGE field" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); fixture.logger.info("listening on port {d} as {s}", .{ 8080, "journalz" }); var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit(); try testing.expectEqualStrings( "listening on port 8080 as journalz", entry.get("MESSAGE").?, ); } test "a cancelled message is never sent" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit(); const msg = try fixture.logger.message(.INFO); msg.cancel(); fixture.logger.info("the only one", .{}); var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit(); try testing.expectEqualStrings("the only one", entry.get("MESSAGE").?); } test "initPath refuses a path too long for sun_path" { const long = "/" ** 108; try testing.expectError( error.PathTooLong, Logger.initPath(testing.io, null, null, long), ); } test "facility and priority carry the syslog numbers" { // These cross the wire as decimal numbers and journald reads them as // syslog's, so the values are part of the protocol rather than an // internal detail. try testing.expectEqual(@as(u5, 0), @intFromEnum(Facility.KERN)); try testing.expectEqual(@as(u5, 11), @intFromEnum(Facility.FTP)); try testing.expectEqual(@as(u5, 16), @intFromEnum(Facility.LOCAL0)); try testing.expectEqual(@as(u5, 23), @intFromEnum(Facility.LOCAL7)); try testing.expectEqual(@as(u3, 0), @intFromEnum(Priority.EMERG)); try testing.expectEqual(@as(u3, 3), @intFromEnum(Priority.ERROR)); try testing.expectEqual(@as(u3, 7), @intFromEnum(Priority.DEBUG)); }