strawberry/tests/test_control_server.cpp
trvon ca9350f0fa
Build on macOS: portable syscalls, sockets and tray
The tree now compiles on macOS. Each Linux-only call gets a Darwin
branch, and the Linux branch stays as it was:

- io::fdatasync uses fcntl(F_FULLFSYNC): fsync alone only reaches the
  drive cache on APFS, and the store's crash atomicity relies on it.
- Control socket: FD_CLOEXEC set after socket/accept/recvmsg (no
  SOCK_CLOEXEC, accept4 or MSG_CMSG_CLOEXEC), SO_NOSIGPIPE, peer
  credentials from LOCAL_PEERCRED + LOCAL_PEERPID, getgrouplist with
  int groups and a growing buffer. launchd has no RuntimeDirectory, so
  the socket directory is created (0750, access group) when missing.
  Default socket path is /var/run/strawberry/control.sock.
- CRC32C detects ARMv8 CRC with hw.optional.armv8_crc32 (no auxv).
- stat mtime via st_mtimespec; the BPF shared header uses stdint
  typedefs off Linux.
- Background threads join the PRIO_DARWIN_BG band (lower CPU and I/O);
  crash safety zeroes RLIMIT_CORE in place of PR_SET_DUMPABLE.
- The desktop app drops Qt DBus off Linux and shows notifications as
  tray messages (app/notifier_tray.cpp).
- make setup passes Homebrew's keg-only libarchive to meson.

Tests: behavior_live (Linux ptrace API) builds on Linux only, the
control-server fd count reads /dev/fd, the crash test checks the core
limit on macOS, and the runtime pipeline test no longer references a
YARA-only helper when YARA is absent (that also broke Linux builds
without libyara).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 20:52:39 -06:00

369 lines
13 KiB
C++

#include "strawberry/control_server.hpp"
#include <atomic>
#include <optional>
#include <cassert>
#include <chrono>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
namespace fs = std::filesystem;
using namespace std::chrono_literals;
namespace {
fs::path make_socket_dir() {
const auto dir = fs::temp_directory_path() / ("strawberry_control_test_" + std::to_string(::getpid()));
std::error_code ec;
fs::remove_all(dir, ec);
fs::create_directories(dir);
return dir;
}
bool contains(const std::string& haystack, const std::string& needle) {
return haystack.find(needle) != std::string::npos;
}
// Send raw bytes (no newline handling) and return whatever comes back.
std::string raw_request(const std::string& path, const std::string& payload) {
const int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
assert(fd >= 0);
sockaddr_un address{};
address.sun_family = AF_UNIX;
std::strncpy(address.sun_path, path.c_str(), sizeof(address.sun_path) - 1);
assert(::connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0);
if (!payload.empty()) {
::send(fd, payload.data(), payload.size(), MSG_NOSIGNAL);
}
::shutdown(fd, SHUT_WR);
std::string reply;
char buffer[512];
ssize_t n = 0;
while ((n = ::recv(fd, buffer, sizeof(buffer), 0)) > 0) {
reply.append(buffer, static_cast<std::size_t>(n));
}
::close(fd);
return reply;
}
void test_verbs_and_rejections() {
std::cout << "Test control verbs and rejections:" << std::endl;
const auto dir = make_socket_dir();
const auto path = (dir / "control.sock").string();
std::atomic<int> reloads{0};
std::atomic<int> rescans{0};
strawberry::ControlServerOptions options;
options.socket_path = path;
options.group = ""; // owner-only
options.rescan_min_interval = 60s;
options.read_timeout = 300ms;
strawberry::ControlHandlers handlers;
handlers.status = []() { return std::string("{\"healthy\":true}"); };
handlers.reload_rules = [&]() { ++reloads; return std::string("{\"reloaded\":true}"); };
handlers.rescan = [&]() { ++rescans; return std::string("{\"queued\":true}"); };
strawberry::ControlServer server;
assert(server.start(options, handlers));
assert(server.is_running());
struct stat st{};
assert(::stat(path.c_str(), &st) == 0);
assert(S_ISSOCK(st.st_mode));
assert((st.st_mode & 0777) == 0600);
std::string error;
auto status = strawberry::control_request(path, "status", 1s, &error);
assert(status);
assert(*status == "{\"ok\":true,\"verb\":\"status\",\"data\":{\"healthy\":true}}");
auto reload = strawberry::control_request(path, "reload-rules", 1s);
assert(reload && contains(*reload, "\"reloaded\":true"));
assert(reloads == 1);
auto rescan = strawberry::control_request(path, "rescan", 1s);
assert(rescan && contains(*rescan, "\"queued\":true"));
auto limited = strawberry::control_request(path, "rescan", 1s);
assert(limited && contains(*limited, "rate limited"));
assert(rescans == 1);
// Arguments, unknown verbs, case changes and smuggling are all rejected.
for (const std::string verb : {"rescan; reboot", "status extra", "STATUS", "shutdown", "", "../status"}) {
auto reply = strawberry::control_request(path, verb, 1s);
assert(reply && contains(*reply, "\"ok\":false"));
}
assert(reloads == 1);
// Oversize request.
const auto oversize = raw_request(path, std::string(200, 'a') + "\n");
assert(contains(oversize, "request too long"));
// Missing newline before the client closes: rejected, not executed.
const auto unterminated = raw_request(path, "reload-rules");
assert(contains(unterminated, "\"ok\":false"));
assert(reloads == 1);
server.stop();
assert(!fs::exists(path));
assert(!strawberry::control_request(path, "status", 200ms, &error));
assert(!error.empty());
fs::remove_all(dir);
std::cout << " PASSED" << std::endl;
}
void test_peer_check_denies() {
std::cout << "Test peer check denies unauthorized peers:" << std::endl;
const auto dir = make_socket_dir();
const auto path = (dir / "control.sock").string();
std::atomic<unsigned> seen_uid{9999};
strawberry::ControlServerOptions options;
options.socket_path = path;
options.peer_check = [&](unsigned uid, unsigned, int pid) {
seen_uid = uid;
assert(pid == ::getpid());
return false;
};
std::atomic<int> reloads{0};
strawberry::ControlHandlers handlers;
handlers.status = []() { return std::string("{}"); };
handlers.reload_rules = [&]() { ++reloads; return std::string("{}"); };
strawberry::ControlServer server;
assert(server.start(options, handlers));
auto reply = strawberry::control_request(path, "reload-rules", 1s);
assert(reply && contains(*reply, "permission denied"));
assert(reloads == 0);
assert(seen_uid == ::getuid());
server.stop();
fs::remove_all(dir);
std::cout << " PASSED" << std::endl;
}
void test_refuses_to_replace_regular_file() {
std::cout << "Test refuses to replace a non-socket file:" << std::endl;
const auto dir = make_socket_dir();
const auto path = dir / "control.sock";
{ std::FILE* f = std::fopen(path.c_str(), "w"); assert(f); std::fclose(f); }
strawberry::ControlServerOptions options;
options.socket_path = path.string();
strawberry::ControlServer server;
assert(!server.start(options, {}));
assert(fs::is_regular_file(path));
fs::remove_all(dir);
std::cout << " PASSED" << std::endl;
}
std::size_t open_fd_count() {
std::size_t count = 0;
for ([[maybe_unused]] const auto& entry : fs::directory_iterator(
#if defined(__linux__)
"/proc/self/fd"
#else
"/dev/fd"
#endif
)) {
++count;
}
return count;
}
// Send `verb\n` with the given descriptors attached (SCM_RIGHTS).
std::string send_with_fds(const std::string& path, const std::string& verb, const std::vector<int>& fds) {
const int sock = ::socket(AF_UNIX, SOCK_STREAM, 0);
assert(sock >= 0);
sockaddr_un address{};
address.sun_family = AF_UNIX;
std::strncpy(address.sun_path, path.c_str(), sizeof(address.sun_path) - 1);
assert(::connect(sock, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0);
const std::string line = verb + "\n";
iovec iov{const_cast<char*>(line.data()), line.size()};
std::vector<char> control(CMSG_SPACE(sizeof(int) * fds.size()));
msghdr msg{};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
if (!fds.empty()) {
msg.msg_control = control.data();
msg.msg_controllen = control.size();
cmsghdr* c = CMSG_FIRSTHDR(&msg);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_RIGHTS;
c->cmsg_len = CMSG_LEN(sizeof(int) * fds.size());
std::memcpy(CMSG_DATA(c), fds.data(), sizeof(int) * fds.size());
}
assert(::sendmsg(sock, &msg, MSG_NOSIGNAL) == static_cast<ssize_t>(line.size()));
std::string reply;
char buffer[512];
ssize_t n = 0;
while ((n = ::recv(sock, buffer, sizeof(buffer), 0)) > 0) {
reply.append(buffer, static_cast<std::size_t>(n));
}
::close(sock);
return reply;
}
void test_scan_fd_passing() {
std::cout << "Test scan-fd descriptor passing:" << std::endl;
const auto dir = make_socket_dir();
const auto path = (dir / "control.sock").string();
const auto file = dir / "sample.bin";
{
std::FILE* f = std::fopen(file.c_str(), "w");
assert(f);
std::fputs("hello-scan", f);
std::fclose(f);
}
std::atomic<int> scans{0};
std::atomic<unsigned> scan_uid{9999};
strawberry::ControlServerOptions options;
options.socket_path = path;
options.scan_rate_per_minute = 3;
strawberry::ControlHandlers handlers;
handlers.status = []() { return std::string("{}"); };
handlers.scan_fd = [&](int fd, unsigned uid, int) {
++scans;
scan_uid = uid;
// The server must hand us the same open file the client opened.
char buffer[32] = {};
const ssize_t n = ::pread(fd, buffer, sizeof(buffer) - 1, 0);
return std::string("{\"content\":\"") + std::string(buffer, n > 0 ? static_cast<std::size_t>(n) : 0) + "\"}";
};
strawberry::ControlServer server;
assert(server.start(options, handlers));
const auto baseline_fds = open_fd_count();
const int fd = ::open(file.c_str(), O_RDONLY | O_CLOEXEC);
assert(fd >= 0);
// Library client.
auto reply = strawberry::control_request_with_fd(path, "scan-fd", fd, 1s);
assert(reply && contains(*reply, "\"content\":\"hello-scan\""));
assert(scan_uid == ::getuid());
// scan-fd without a descriptor.
reply = strawberry::control_request(path, "scan-fd", 1s);
assert(reply && contains(*reply, "exactly one file descriptor"));
// A descriptor smuggled onto another verb is rejected (and closed).
auto raw = send_with_fds(path, "status", {fd});
assert(contains(raw, "unexpected file descriptor"));
// Two descriptors.
raw = send_with_fds(path, "scan-fd", {fd, fd});
assert(contains(raw, "exactly one file descriptor"));
// Rate limit: capacity 3/min, one already used.
assert(contains(send_with_fds(path, "scan-fd", {fd}), "hello-scan"));
assert(contains(send_with_fds(path, "scan-fd", {fd}), "hello-scan"));
assert(contains(send_with_fds(path, "scan-fd", {fd}), "rate limited"));
assert(scans == 3);
::close(fd);
// Every descriptor the server received was closed again.
assert(open_fd_count() == baseline_fds);
server.stop();
fs::remove_all(dir);
std::cout << " PASSED" << std::endl;
}
void test_payload_verbs() {
std::cout << "Test payload verbs, policy and update-rules:" << std::endl;
const auto dir = make_socket_dir();
const auto path = (dir / "control.sock").string();
std::vector<std::string> received;
strawberry::ControlServerOptions options;
options.socket_path = path;
options.policy_change_rate_per_minute = 3;
options.update_min_interval = 60s;
strawberry::ControlHandlers handlers;
handlers.status = []() { return std::string("{}"); };
handlers.policy = []() { return std::string(R"({"policy":{}})"); };
handlers.update_rules = []() { return std::string(R"({"requested":true})"); };
handlers.policy_change = [&](const std::string& verb, const std::string& payload, unsigned uid, int,
std::string& error) -> std::optional<std::string> {
assert(uid == ::getuid());
received.push_back(verb + " " + payload);
if (payload.find("bad") != std::string::npos) {
error = "invalid entry";
return std::nullopt;
}
return std::string(R"({"applied":true})");
};
strawberry::ControlServer server;
assert(server.start(options, handlers));
auto reply = strawberry::control_request_with_payload(path, "allowlist-add", R"({"kind":"rule","value":"X"})", 1s);
assert(reply && contains(*reply, "\"applied\":true"));
assert(received.back() == R"(allowlist-add {"kind":"rule","value":"X"})");
reply = strawberry::control_request_with_payload(path, "feed-remove", R"({"bad":1})", 1s);
assert(reply && contains(*reply, "invalid entry"));
// Payload on an argument-free verb is rejected.
assert(contains(raw_request(path, "status\n{\"x\":1}\n"), "unexpected data after command"));
// Payload verb without its payload line.
assert(contains(raw_request(path, "allowlist-add\n"), "missing payload line"));
// Oversize payload.
assert(contains(raw_request(path, "allowlist-add\n" + std::string(9000, 'x') + "\n"), "payload too long"));
// Extra line after the payload.
assert(contains(raw_request(path, "allowlist-add\n{}\nmore\n"), "unexpected data after payload"));
// Payload containing a newline cannot be sent by the client helper.
std::string error;
assert(!strawberry::control_request_with_payload(path, "allowlist-add", "{}\nrescan", 1s, &error));
// Rate limit: 3 per minute (2 already used).
reply = strawberry::control_request_with_payload(path, "allowlist-remove", R"({"id":"a"})", 1s);
assert(reply && contains(*reply, "applied"));
reply = strawberry::control_request_with_payload(path, "allowlist-remove", R"({"id":"b"})", 1s);
assert(reply && contains(*reply, "rate limited"));
assert(received.size() == 3);
auto policy = strawberry::control_request(path, "policy", 1s);
assert(policy && contains(*policy, "\"policy\":{}"));
auto update = strawberry::control_request(path, "update-rules", 1s);
assert(update && contains(*update, "requested"));
update = strawberry::control_request(path, "update-rules", 1s);
assert(update && contains(*update, "update rate limited"));
server.stop();
fs::remove_all(dir);
std::cout << " PASSED" << std::endl;
}
} // namespace
int main() {
std::cout << "Running ControlServer tests..." << std::endl << std::endl;
test_verbs_and_rejections();
test_peer_check_denies();
test_refuses_to_replace_regular_file();
test_scan_fd_passing();
test_payload_verbs();
std::cout << std::endl << "All tests passed!" << std::endl;
return 0;
}