strawberry/tests/test_process_monitor.cpp
trvon ad1676a594
Some checks failed
Build and Test / build (debug, clang) (push) Has been cancelled
Build and Test / build (debug, gcc) (push) Has been cancelled
Build and Test / build (release, clang) (push) Has been cancelled
Build and Test / build (release, gcc) (push) Has been cancelled
Build and Test / docker (push) Has been cancelled
Integrate features into the daemon, build and docs
Wire the policy, feeds, containment, exec guard, behavior, governor,
crash safety and event store into the daemon, detection pipeline, CLI
and meson build (zstd now required); Dockerfile, conan, systemd unit
(LimitCORE=0, resource limits) and installer updates; existing tests
adapted (store paths are directories now). Detections are counted and
notified even when evidence cannot be persisted (persist_failures in
status). prevention_timeout_ms is clamped and behavior dedupe handles
out-of-order events. Docs: API contract, developer guide, plan, UX,
agent rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:17:30 -06:00

342 lines
11 KiB
C++

#include "strawberry/hash_utils.hpp"
#include "strawberry/process_monitor.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#if defined(_WIN32)
#include <stdlib.h>
#endif
namespace fs = std::filesystem;
namespace {
fs::path make_test_root() {
const auto root = fs::temp_directory_path() / "strawberry_process_monitor_tests";
std::error_code ec;
fs::remove_all(root, ec);
fs::create_directories(root);
return root;
}
void write_binary_file(const fs::path& path, const std::vector<unsigned char>& content) {
if (path.has_parent_path()) {
fs::create_directories(path.parent_path());
}
std::ofstream output(path, std::ios::binary);
assert(output.good());
output.write(reinterpret_cast<const char*>(content.data()),
static_cast<std::streamsize>(content.size()));
output.close();
assert(output.good());
}
void write_cmdline_file(const fs::path& path, const std::vector<std::string>& args) {
if (path.has_parent_path()) {
fs::create_directories(path.parent_path());
}
std::ofstream output(path, std::ios::binary);
assert(output.good());
for (const auto& arg : args) {
output.write(arg.data(), static_cast<std::streamsize>(arg.size()));
output.put('\0');
}
output.close();
assert(output.good());
}
void write_status_file(const fs::path& path, int parent_pid) {
if (path.has_parent_path()) {
fs::create_directories(path.parent_path());
}
std::ofstream output(path);
assert(output.good());
output << "Name:\tsynthetic\n";
output << "State:\tR (running)\n";
output << "PPid:\t" << parent_pid << "\n";
output.close();
assert(output.good());
}
void set_env_var(const std::string& key, const std::string& value) {
#if defined(_WIN32)
_putenv_s(key.c_str(), value.c_str());
#else
::setenv(key.c_str(), value.c_str(), 1);
#endif
}
void unset_env_var(const std::string& key) {
#if defined(_WIN32)
_putenv_s(key.c_str(), "");
#else
::unsetenv(key.c_str());
#endif
}
void test_initialize_rejects_missing_proc_root() {
unset_env_var("STRAWBERRY_PROCFS_ROOT");
set_env_var("STRAWBERRY_PROCFS_ROOT", "/definitely/not/a/real/procfs/root");
strawberry::ProcessMonitor monitor;
std::cout << "Test initialize_rejects_missing_proc_root:" << std::endl;
assert(!monitor.initialize());
std::cout << " PASSED" << std::endl;
unset_env_var("STRAWBERRY_PROCFS_ROOT");
}
void test_detects_new_process_from_procfs_snapshot() {
const auto root = make_test_root();
const auto executable = root / "bin" / "sample_exec";
write_binary_file(executable, {0x7f, 0x45, 0x4c, 0x46, 0x01, 0x02, 0x03, 0x04});
const auto expected_hash = strawberry::HashUtils::sha256_file(executable.string());
assert(!expected_hash.empty());
const auto existing_proc_dir = root / "100";
fs::create_directories(existing_proc_dir);
std::error_code ec;
fs::create_symlink(executable, existing_proc_dir / "exe", ec);
assert(!ec);
write_cmdline_file(existing_proc_dir / "cmdline", {"already-running"});
write_status_file(existing_proc_dir / "status", 1);
set_env_var("STRAWBERRY_PROCFS_ROOT", root.string());
set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25");
strawberry::ProcessMonitor monitor;
std::mutex mutex;
std::condition_variable cv;
std::vector<strawberry::ProcessInfo> events;
std::cout << "Test detects_new_process_from_procfs_snapshot:" << std::endl;
assert(monitor.initialize());
assert(monitor.start([&](const strawberry::ProcessInfo& info) {
{
std::lock_guard<std::mutex> lock(mutex);
events.push_back(info);
}
cv.notify_all();
}));
const auto staged_proc_dir = root / "pending-200";
fs::create_directories(staged_proc_dir);
fs::create_symlink(executable, staged_proc_dir / "exe", ec);
assert(!ec);
write_cmdline_file(staged_proc_dir / "cmdline", {"sample_exec", "--flag", "value"});
write_status_file(staged_proc_dir / "status", 100);
const auto new_proc_dir = root / "200";
fs::rename(staged_proc_dir, new_proc_dir, ec);
assert(!ec);
{
std::unique_lock<std::mutex> lock(mutex);
const bool observed = cv.wait_for(lock, std::chrono::seconds(2), [&]() {
return !events.empty();
});
assert(observed);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
monitor.stop();
assert(events.size() == 1);
assert(events[0].pid == 200);
assert(events[0].parent_pid == 100);
assert(events[0].event_timestamp_ns != 0);
assert(events[0].executable_path == executable.string());
assert(events[0].hash.empty()); // hashed by the pipeline, not the monitor thread
assert(events[0].cmdline == "sample_exec --flag value");
std::cout << " PASSED" << std::endl;
unset_env_var("STRAWBERRY_PROCFS_ROOT");
unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS");
fs::remove_all(root, ec);
}
void test_emits_existing_processes_when_enabled() {
const auto root = make_test_root();
const auto executable = root / "bin" / "sample_exec";
write_binary_file(executable, {0x7f, 0x45, 0x4c, 0x46, 0x0a, 0x0b, 0x0c, 0x0d});
const auto expected_hash = strawberry::HashUtils::sha256_file(executable.string());
assert(!expected_hash.empty());
const auto existing_proc_dir = root / "321";
fs::create_directories(existing_proc_dir);
std::error_code ec;
fs::create_symlink(executable, existing_proc_dir / "exe", ec);
assert(!ec);
write_cmdline_file(existing_proc_dir / "cmdline", {"already-running", "--inventory"});
write_status_file(existing_proc_dir / "status", 12);
set_env_var("STRAWBERRY_PROCFS_ROOT", root.string());
set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25");
strawberry::ProcessMonitorOptions options;
options.emit_existing_processes = true;
strawberry::ProcessMonitor monitor;
std::mutex mutex;
std::condition_variable cv;
std::vector<strawberry::ProcessInfo> events;
std::cout << "Test emits_existing_processes_when_enabled:" << std::endl;
assert(monitor.initialize(options));
assert(monitor.start([&](const strawberry::ProcessInfo& info) {
{
std::lock_guard<std::mutex> lock(mutex);
events.push_back(info);
}
cv.notify_all();
}));
{
std::unique_lock<std::mutex> lock(mutex);
const bool observed = cv.wait_for(lock, std::chrono::seconds(2), [&]() {
return !events.empty();
});
assert(observed);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
monitor.stop();
assert(events.size() == 1);
assert(events[0].pid == 321);
assert(events[0].parent_pid == 12);
assert(events[0].event_timestamp_ns != 0);
assert(events[0].executable_path == executable.string());
assert(events[0].hash.empty()); // hashed by the pipeline, not the monitor thread
assert(events[0].cmdline == "already-running --inventory");
assert(events[0].from_inventory);
std::cout << " PASSED" << std::endl;
unset_env_var("STRAWBERRY_PROCFS_ROOT");
unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS");
fs::remove_all(root, ec);
}
void test_enriches_identity_and_flags_deleted_and_memfd_images() {
const auto root = make_test_root();
const auto executable = root / "bin" / "identity_exec";
write_binary_file(executable, {0x7f, 0x45, 0x4c, 0x46, 0x09});
std::error_code ec;
fs::create_directories(root / "sys" / "kernel" / "random");
{
std::ofstream boot(root / "sys" / "kernel" / "random" / "boot_id");
boot << "0123abcd-ef45-6789-0123-456789abcdef\n";
}
const auto write_stat = [](const fs::path& path, int pid, uint64_t start_ticks) {
std::ofstream stat(path);
// comm containing spaces and ')' must not shift the field count.
stat << pid << " (evil) name) S 1 1 1 0 -1 4194304 0 0 0 0 0 0 0 0 20 0 1 0 "
<< start_ticks << " 1000 100 18446744073709551615\n";
};
// Parent 300 is running; 301 runs a deleted binary; 302 runs from a memfd.
fs::create_directories(root / "300");
write_stat(root / "300" / "stat", 300, 1111);
set_env_var("STRAWBERRY_PROCFS_ROOT", root.string());
set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25");
strawberry::ProcessMonitor monitor;
std::mutex mutex;
std::condition_variable cv;
std::vector<strawberry::ProcessInfo> events;
std::cout << "Test enriches_identity_and_flags_deleted_and_memfd_images:" << std::endl;
assert(monitor.initialize());
assert(monitor.start([&](const strawberry::ProcessInfo& info) {
{
std::lock_guard<std::mutex> lock(mutex);
events.push_back(info);
}
cv.notify_all();
}));
const auto stage = [&](int pid, const fs::path& link_target, uint64_t start_ticks) {
const auto staged = root / ("pending-" + std::to_string(pid));
fs::create_directories(staged);
fs::create_symlink(link_target, staged / "exe", ec);
assert(!ec);
write_cmdline_file(staged / "cmdline", {"identity_exec"});
write_status_file(staged / "status", 300);
write_stat(staged / "stat", pid, start_ticks);
fs::rename(staged, root / std::to_string(pid), ec);
assert(!ec);
};
stage(301, fs::path(executable.string() + " (deleted)"), 2222);
stage(302, fs::path("/memfd:payload (deleted)"), 3333);
{
std::unique_lock<std::mutex> lock(mutex);
const bool observed = cv.wait_for(lock, std::chrono::seconds(2), [&]() {
return events.size() >= 2;
});
assert(observed);
}
monitor.stop();
std::sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a.pid < b.pid; });
const auto& deleted = events[0];
assert(deleted.pid == 301);
assert(deleted.executable_deleted);
assert(!deleted.executable_memfd);
assert(deleted.executable_path == executable.string());
assert(deleted.image_path == (root / "301" / "exe").string());
assert(deleted.start_time_ticks == 2222);
assert(deleted.parent_start_time_ticks == 1111);
assert(deleted.boot_id == "0123abcdef45678901234567" "89abcdef");
assert(strawberry::process_node_id(deleted) == "process_301_0123abcd_2222");
assert(strawberry::parent_process_node_id(deleted) == "process_300_0123abcd_1111");
const auto& memfd = events[1];
assert(memfd.pid == 302);
assert(memfd.executable_memfd);
assert(memfd.executable_deleted);
assert(memfd.executable_path == "/memfd:payload");
std::cout << " PASSED" << std::endl;
unset_env_var("STRAWBERRY_PROCFS_ROOT");
unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS");
fs::remove_all(root, ec);
}
} // namespace
int main() {
std::cout << "Running ProcessMonitor tests..." << std::endl << std::endl;
test_initialize_rejects_missing_proc_root();
test_detects_new_process_from_procfs_snapshot();
test_emits_existing_processes_when_enabled();
test_enriches_identity_and_flags_deleted_and_memfd_images();
std::cout << std::endl << "All tests passed!" << std::endl;
return 0;
}