strawberry/tests/test_daemon_runtime.cpp
trvon be237d6040
Findings: reconcile evidence and harden policy rebuilds
Preserve independent support, typed rule namespaces and stable process lifetimes. Share authoritative managed-set reconciliation across daemon and offline correlation, load offline policy without seeding/migration, and release resources after shutdown-flush exceptions. Keep retirement history, transaction ownership and fault/allocation regressions; no whole-set crash-atomicity or live acceptance claim.
2026-11-03 06:55:47 -07:00

689 lines
31 KiB
C++

#include "strawberry/daemon_app.hpp"
#include "strawberry/database.hpp"
#include "strawberry/hash_utils.hpp"
#include "strawberry/control_server.hpp"
#include "strawberry/behavior_engine.hpp"
#include "strawberry/node_ids.hpp"
#include "strawberry/store/log_store.hpp"
#include "strawberry/telemetry.hpp"
#include "strawberry/learn/model_file.hpp"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <stdlib.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <signal.h>
#include <optional>
#include <sys/wait.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <sys/sysctl.h>
#endif
#ifndef STRAWBERRY_HAVE_YARA
#define STRAWBERRY_HAVE_YARA 0
#endif
namespace fs = std::filesystem;
namespace {
#if STRAWBERRY_HAVE_YARA
fs::path make_test_root() {
const auto root = fs::temp_directory_path() / "strawberry_daemon_runtime_tests";
std::error_code ec;
fs::remove_all(root, ec);
fs::create_directories(root, ec);
assert(!ec);
return root;
}
void write_binary_file(const fs::path& path, const std::string& content) {
if (path.has_parent_path()) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
assert(!ec);
}
std::ofstream output(path, std::ios::binary);
assert(output.good());
output.write(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()) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
assert(!ec);
}
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()) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
assert(!ec);
}
std::ofstream output(path);
assert(output.good());
output << "Name:\tsynthetic-daemon\n";
output << "State:\tR (running)\n";
output << "PPid:\t" << parent_pid << "\n";
output.close();
assert(output.good());
}
void write_rule_file(const fs::path& path) {
if (path.has_parent_path()) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
assert(!ec);
}
std::ofstream output(path);
assert(output.good());
output << "rule SyntheticDaemonRule {\n"
" strings:\n"
" $marker = \"synthetic-daemon-marker\"\n"
" condition:\n"
" $marker\n"
"}\n";
output.close();
assert(output.good());
}
void write_config_file(const fs::path& path,
const std::string& db_path,
const std::string& rules_dir) {
if (path.has_parent_path()) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
assert(!ec);
}
std::ofstream output(path);
assert(output.good());
output << "db_path=" << db_path << "\n";
output << "yara_rules_path=" << rules_dir << "\n";
output << "daemonize=false\n";
output << "enable_bpf_monitoring=true\n";
output << "privacy_trackers=false\n"; // not under test; avoid binding the ingest socket
output << "control_socket_path=" << (path.parent_path() / "control.sock").string() << "\n";
output << "control_group=\n"; // keep this synthetic daemon off the host's live control socket
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
}
bool wait_for_running(strawberry::StrawberryDaemon& daemon, std::chrono::milliseconds timeout) {
const auto deadline = std::chrono::steady_clock::now() + timeout;
while (std::chrono::steady_clock::now() < deadline) {
if (daemon.is_running()) {
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
return daemon.is_running();
}
void test_daemon_procfs_event_persists_match() {
const auto root = make_test_root();
const auto proc_root = root / "proc";
const auto rules_dir = root / "rules";
const auto executable = root / "bin" / "synthetic_daemon_exec";
const auto database_path = (root / "daemon_runtime.db").string();
const auto config_path = root / "strawberry.conf";
std::error_code ec;
fs::create_directories(proc_root, ec);
assert(!ec);
fs::create_directories(rules_dir, ec);
assert(!ec);
write_binary_file(executable, std::string("\x7f\x45\x4c\x46") + "synthetic-daemon-marker");
write_rule_file(rules_dir / "synthetic_daemon.yar");
write_config_file(config_path, database_path, rules_dir.string());
const auto expected_hash = strawberry::HashUtils::sha256_file(executable.string());
assert(!expected_hash.empty());
set_env_var("STRAWBERRY_PROCFS_ROOT", proc_root.string());
set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25");
strawberry::StrawberryDaemon daemon;
std::cout << "Test daemon_procfs_event_persists_match:" << std::endl;
assert(daemon.initialize(config_path.string()));
assert(daemon.is_initialized());
std::thread daemon_thread([&]() {
daemon.run();
});
assert(wait_for_running(daemon, std::chrono::seconds(2)));
const auto staged_proc_dir = proc_root / "pending-654";
fs::create_directories(staged_proc_dir, ec);
assert(!ec);
fs::create_symlink(executable, staged_proc_dir / "exe", ec);
assert(!ec);
write_cmdline_file(staged_proc_dir / "cmdline", {"synthetic_daemon_exec", "--daemon-test"});
write_status_file(staged_proc_dir / "status", 42);
const auto live_proc_dir = proc_root / "654";
fs::rename(staged_proc_dir, live_proc_dir, ec);
assert(!ec);
std::this_thread::sleep_for(std::chrono::seconds(1));
daemon.request_stop();
daemon_thread.join();
assert(!daemon.is_running());
strawberry::Database database;
assert(database.open(database_path));
auto hits = database.find_indicators_by_hash(expected_hash);
assert(hits.size() == 1);
assert(hits[0].rule_name == "SyntheticDaemonRule");
assert(hits[0].metadata.at("source") == "yara");
assert(hits[0].metadata.at("scan_kind") == "process_executable");
assert(hits[0].metadata.at("pid") == "654");
assert(hits[0].metadata.at("parent_pid") == "42");
assert(hits[0].metadata.at("process_path") == executable.string());
assert(hits[0].metadata.at("cmdline") == "synthetic_daemon_exec --daemon-test");
assert(!hits[0].metadata.at("event_timestamp_ns").empty());
const std::string process_node_id = "process_654";
const std::string file_node_id = "file_" + expected_hash;
auto related = database.find_related_nodes(process_node_id, 1);
assert(related.size() == 2);
bool saw_indicator = false;
bool saw_file = false;
for (const auto& node : related) {
if (node.type == "indicator") {
saw_indicator = true;
assert(node.properties.at("rule_name") == "SyntheticDaemonRule");
assert(node.properties.at("cmdline") == "synthetic_daemon_exec --daemon-test");
assert(node.properties.at("parent_pid") == "42");
} else if (node.id == file_node_id) {
saw_file = true;
assert(node.type == "file");
assert(node.properties.at("path") == executable.string());
assert(node.properties.at("hash") == expected_hash);
assert(node.properties.at("kind") == "executable_image");
}
}
assert(saw_indicator);
assert(saw_file);
auto edges = database.get_node_edges(process_node_id);
assert(edges.size() == 3);
bool saw_spawned = false;
bool saw_executed = false;
bool saw_matched = false;
for (const auto& edge : edges) {
if (edge.relationship_type == "spawned") {
saw_spawned = true;
} else if (edge.relationship_type == "executed") {
saw_executed = true;
assert(edge.to_id == file_node_id);
} else if (edge.relationship_type == "matched") {
saw_matched = true;
}
}
assert(saw_spawned);
assert(saw_executed);
assert(saw_matched);
auto parent_related = database.find_related_nodes("process_42", 1);
assert(parent_related.size() == 1);
assert(parent_related[0].id == process_node_id);
auto file_edges = database.get_node_edges(file_node_id);
assert(file_edges.size() == 3); // executed, content_matched, same_path
bool saw_content_matched = false;
bool saw_same_path = false;
for (const auto& edge : file_edges) {
if (edge.relationship_type == "content_matched") {
saw_content_matched = true;
} else if (edge.relationship_type == strawberry::kSamePathRelationship) {
// The path id (used by path-keyed evidence) points at this content id.
saw_same_path = edge.to_id == file_node_id && edge.from_id.rfind("file_path_", 0) == 0;
}
}
assert(saw_content_matched);
assert(saw_same_path);
database.close();
std::cout << " PASSED" << std::endl;
unset_env_var("STRAWBERRY_PROCFS_ROOT");
unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS");
fs::remove_all(root, ec);
}
bool contains_text(const std::string& haystack, const std::string& needle) {
return haystack.find(needle) != std::string::npos;
}
void test_daemon_opensnitch_containment() {
const auto root = make_test_root();
const auto proc_root = root / "proc";
const auto rules_dir = root / "rules";
const auto os_rules = root / "opensnitch" / "rules";
const auto executable = root / "bin" / "contain_me";
const auto socket_path = (fs::temp_directory_path() / ("sbd-" + std::to_string(::getpid()) + ".sock")).string();
const auto config_path = root / "strawberry.conf";
std::error_code ec;
fs::create_directories(proc_root, ec);
fs::create_directories(os_rules, ec);
fs::create_directories(rules_dir, ec);
write_binary_file(executable, std::string("\x7f\x45\x4c\x46") + "contain-marker");
{
std::ofstream rule(rules_dir / "high.yar");
rule << "rule High_Severity_Test { meta: severity = \"high\" strings: $m = \"contain-marker\" condition: $m }\n";
}
// OpenSnitch config with checksums on, so rules are hash-pinned.
std::ofstream(root / "opensnitch" / "default-config.json") << R"({"Rules":{"EnableChecksums":true}})";
{
std::ofstream config(config_path);
config << "db_path=" << (root / "daemon.db").string() << "\n"
<< "yara_rules_path=" << rules_dir.string() << "\n"
<< "enable_bpf_monitoring=true\n"
<< "control_socket_path=" << socket_path << "\n"
<< "control_group=\n"
<< "opensnitch_rules_dir=" << os_rules.string() << "\n"
<< "opensnitch_config=" << (root / "opensnitch" / "default-config.json").string() << "\n"
<< "privacy_trackers=false\n"; // not under test; avoid binding the ingest socket
}
const auto hash = strawberry::HashUtils::sha256_file(executable.string());
const auto rule_file = os_rules / ("strawberry-contain-" + hash.substr(0, 12) + ".json");
set_env_var("STRAWBERRY_PROCFS_ROOT", proc_root.string());
set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25");
std::cout << "Test daemon_opensnitch_containment:" << std::endl;
strawberry::StrawberryDaemon daemon;
assert(daemon.initialize(config_path.string()));
std::thread runner([&]() { daemon.run(); });
assert(wait_for_running(daemon, std::chrono::seconds(2)));
const auto staged = proc_root / "pending-777";
fs::create_directories(staged, ec);
fs::create_symlink(executable, staged / "exe", ec);
write_cmdline_file(staged / "cmdline", {"contain_me"});
write_status_file(staged / "status", 1);
fs::rename(staged, proc_root / "777", ec);
// Auto-containment: high severity, not a system path.
for (int i = 0; i < 80 && !fs::exists(rule_file); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
assert(fs::exists(rule_file));
{
std::ifstream input(rule_file);
const std::string text((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
assert(contains_text(text, "process.hash.md5") && contains_text(text, executable.string()));
}
auto status = strawberry::control_request(socket_path, "status", std::chrono::seconds(2));
assert(status && contains_text(*status, "\"containments\":1"));
// Resource governor + timing surfaces.
assert(contains_text(*status, "\"resources\":{\"cgroup\"") || contains_text(*status, "\"resources\":{"));
assert(contains_text(*status, "\"profile\":\"balanced\""));
assert(contains_text(*status, "\"level\":\""));
assert(contains_text(*status, "\"timings\":{"));
assert(contains_text(*status, "\"exec_decision\":{\"count\""));
assert(contains_text(*status, "\"model\":{") && contains_text(*status, "\"shadow_enabled\":true"));
auto policy = strawberry::control_request(socket_path, "policy", std::chrono::seconds(2));
assert(policy && contains_text(*policy, "\"automatic\":true"));
// The high-severity detection above must be correlated into a stored
// finding for this binary before we allowlist it. retire-superseded-findings
// runs correlation synchronously, so after this call a finding exists.
// dry-run count of *allowlisted*-stale findings is the socket-visible gauge
// we use below (it forces correlation each time it is called).
auto allowlisted_stale = [&]() -> int {
auto r = strawberry::control_request_with_payload(socket_path, "maintain",
R"({"action":"retire-allowlisted-findings","dry_run":true})", std::chrono::seconds(5));
if (!r) return -1;
const auto doc = nlohmann::json::parse(*r, nullptr, false);
if (!doc.is_object() || !doc.contains("data") || !doc["data"].is_object()) return -1;
return doc["data"].value("count", -1);
};
auto force_correlation = [&]() {
(void) strawberry::control_request_with_payload(socket_path, "maintain",
R"({"action":"retire-superseded-findings","dry_run":true})", std::chrono::seconds(5));
};
force_correlation(); // materialise the finding for the detected binary
// Not allowlisted yet, so no finding is counted as allowlisted-stale.
assert(allowlisted_stale() == 0);
// Allowlisting the binary releases its containment AND retires the findings
// already stored for it, reporting how many. This is the regression guard
// for the ss false positive: the old allowlist-add suppressed only *new*
// detections and left the stored ones for a separate maintenance command no
// operator ran, so every reload re-surfaced ~9k findings.
auto reply = strawberry::control_request_with_payload(socket_path, "allowlist-add",
R"({"kind":"sha256","value":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"ok\":true"));
assert(contains_text(*reply, "\"retired_findings\":"));
{
const auto doc = nlohmann::json::parse(*reply, nullptr, false);
assert(doc.is_object() && doc.contains("data") && doc["data"].value("retired_findings", 0) >= 1);
}
assert(!fs::exists(rule_file));
// The stored findings are gone and stay gone even after correlation runs
// again: A makes correlation skip allowlisted entities, so it never
// regenerates them. If it did, the regenerated finding would reference the
// now-allowlisted hash and count as allowlisted-stale (> 0).
force_correlation();
assert(allowlisted_stale() == 0);
// Manual containment works only for binaries in stored evidence, and takes
// path/md5 from that evidence.
reply = strawberry::control_request_with_payload(socket_path, "contain-add",
R"({"sha256":")" + std::string(64, 'e') + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "no stored evidence"));
reply = strawberry::control_request_with_payload(socket_path, "contain-add",
R"({"sha256":")" + hash + R"(","path":"/etc/passwd"})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "payload must be"));
reply = strawberry::control_request_with_payload(socket_path, "contain-add",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"hash_pinned\":true"));
assert(fs::exists(rule_file));
// Undo by id.
const auto id_at = reply->find("\"id\":\"") + 6;
const auto id = reply->substr(id_at, reply->find('"', id_at) - id_at);
assert(id.starts_with("contain-"));
reply = strawberry::control_request_with_payload(socket_path, "contain-remove", R"({"id":")" + id + R"("})",
std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"removed\""));
assert(!fs::exists(rule_file));
// Protection settings are validated.
reply = strawberry::control_request_with_payload(socket_path, "protection-set",
R"({"prevention_mode":"yolo"})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "prevention_mode must be"));
reply = strawberry::control_request_with_payload(socket_path, "protection-set",
R"({"contain_auto":false,"contain_min_severity":"critical"})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"contain_auto\":false"));
// Quarantine: only binaries from stored evidence; undo releases containment.
reply = strawberry::control_request_with_payload(socket_path, "quarantine",
R"({"sha256":")" + std::string(64, 'e') + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "no stored evidence"));
reply = strawberry::control_request_with_payload(socket_path, "quarantine",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"quarantined\""));
assert(fs::exists(rule_file));
policy = strawberry::control_request(socket_path, "policy", std::chrono::seconds(2));
assert(policy && contains_text(*policy, hash));
reply = strawberry::control_request_with_payload(socket_path, "quarantine",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "already quarantined"));
reply = strawberry::control_request_with_payload(socket_path, "quarantine-remove",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"released\""));
assert(!fs::exists(rule_file));
// A containment that existed before the quarantine survives its release.
reply = strawberry::control_request_with_payload(socket_path, "contain-add",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && fs::exists(rule_file));
reply = strawberry::control_request_with_payload(socket_path, "quarantine",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"quarantined\""));
reply = strawberry::control_request_with_payload(socket_path, "quarantine-remove",
R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"released\"") && fs::exists(rule_file));
// Process actions: stable ids only, re-verified against the live process.
const auto self_id = strawberry::resolve_process_ref(::getpid());
assert(self_id);
reply = strawberry::control_request_with_payload(socket_path, "process-kill",
R"({"node_id":"process_)" + std::to_string(::getpid()) + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "stable process id"));
reply = strawberry::control_request_with_payload(socket_path, "process-kill",
R"({"node_id":")" + self_id->node_id + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "protected")); // the daemon itself
if (const auto init = strawberry::resolve_process_ref(1)) {
reply = strawberry::control_request_with_payload(socket_path, "process-kill",
R"({"node_id":")" + init->node_id + R"("})", std::chrono::seconds(2));
assert(reply && (contains_text(*reply, "protected") || contains_text(*reply, "no longer running")));
}
const pid_t child = ::fork();
if (child == 0) {
::execl("/bin/sleep", "sleep", "30", static_cast<char*>(nullptr));
::_exit(127);
}
std::optional<strawberry::ProcessRef> child_ref;
for (int i = 0; i < 80; ++i) {
child_ref = strawberry::resolve_process_ref(child);
if (child_ref && child_ref->exe.find("sleep") != std::string::npos) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
assert(child_ref);
// Wrong start time (as after PID reuse) is refused.
auto stale = child_ref->node_id;
stale.back() = stale.back() == '1' ? '2' : '1';
reply = strawberry::control_request_with_payload(socket_path, "process-suspend",
R"({"node_id":")" + stale + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "no longer running"));
const auto state_of = [&]() {
#if defined(__APPLE__)
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, child};
kinfo_proc info{};
std::size_t size = sizeof(info);
if (::sysctl(mib, 4, &info, &size, nullptr, 0) != 0 || size != sizeof(info)) {
return '?';
}
return info.kp_proc.p_stat == SSTOP ? 'T' : 'R';
#else
std::ifstream stat("/proc/" + std::to_string(child) + "/stat");
std::string text((std::istreambuf_iterator<char>(stat)), std::istreambuf_iterator<char>());
const auto close = text.rfind(')');
return close == std::string::npos || close + 2 >= text.size() ? '?' : text[close + 2];
#endif
};
reply = strawberry::control_request_with_payload(socket_path, "process-suspend",
R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"done\""));
for (int i = 0; i < 40 && state_of() != 'T'; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
assert(state_of() == 'T');
reply = strawberry::control_request_with_payload(socket_path, "process-resume",
R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"done\""));
reply = strawberry::control_request_with_payload(socket_path, "scan-memory",
R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"queued\":true"));
reply = strawberry::control_request_with_payload(socket_path, "process-kill",
R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2));
assert(reply && contains_text(*reply, "\"done\""));
int wstatus = 0;
assert(::waitpid(child, &wstatus, 0) == child && WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGKILL);
policy = strawberry::control_request(socket_path, "policy", std::chrono::seconds(2));
assert(policy && contains_text(*policy, "process-kill"));
// Doctor and maintenance through the control socket.
auto doctor = strawberry::control_request(socket_path, "doctor", std::chrono::seconds(5));
assert(doctor && contains_text(*doctor, "\"checks\"") && contains_text(*doctor, "store.health"));
reply = strawberry::control_request_with_payload(socket_path, "maintain",
R"({"action":"retire-superseded-findings","dry_run":true})", std::chrono::seconds(5));
assert(reply && contains_text(*reply, "\"ok\":true") && contains_text(*reply, "\"dry_run\":true"));
reply = strawberry::control_request_with_payload(socket_path, "maintain", R"({"action":"rm-rf"})",
std::chrono::seconds(5));
assert(reply && contains_text(*reply, "unknown action"));
daemon.request_stop();
runner.join();
// Operator actions are labels, policy changes are generations, and the
// run is bracketed by lifecycle records, all in the evidence stream.
std::vector<strawberry::LabelRecord> labels;
std::vector<strawberry::LifecycleEvent> lifecycle;
std::vector<std::string> policy_actions;
strawberry::store::scan_store_read_only((root / "daemon.db").string(), strawberry::store::Stream::evidence,
[&](uint32_t type, std::string_view payload) {
using strawberry::store::RecordType;
if (type == static_cast<uint32_t>(RecordType::label)) {
strawberry::LabelRecord label;
assert(strawberry::decode_label(payload, label));
if (label.source == "operator") labels.push_back(label);
} else if (type == static_cast<uint32_t>(RecordType::lifecycle)) {
strawberry::LifecycleRecord record;
assert(strawberry::decode_lifecycle(payload, record));
lifecycle.push_back(record.event);
} else if (type == static_cast<uint32_t>(RecordType::policy_generation)) {
strawberry::PolicyGenerationRecord record;
assert(strawberry::decode_policy_generation(payload, record));
assert(record.digest.size() == 64);
policy_actions.push_back(record.action);
}
});
assert(lifecycle.size() == 2 && lifecycle[0] == strawberry::LifecycleEvent::start &&
lifecycle[1] == strawberry::LifecycleEvent::stop);
const auto find_label = [&](const std::string& action) {
return std::find_if(labels.begin(), labels.end(), [&](const auto& l) { return l.action == action; });
};
const auto allow = find_label("allowlist-add");
assert(allow != labels.end() && allow->polarity == strawberry::LabelPolarity::negative && allow->sha256 == hash);
const auto kill = find_label("process-kill");
assert(kill != labels.end() && kill->polarity == strawberry::LabelPolarity::positive &&
kill->process_node_id == child_ref->node_id);
assert(find_label("scan-memory") == labels.end()); // not a judgment
assert(std::find(policy_actions.begin(), policy_actions.end(), "allowlist-add") != policy_actions.end());
unset_env_var("STRAWBERRY_PROCFS_ROOT");
unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS");
fs::remove_all(root, ec);
std::cout << " PASSED" << std::endl;
}
void test_model_loading_and_restart() {
const auto root = make_test_root();
const auto rules = root / "rules";
const auto proc = root / "proc";
const auto models = root / "models";
fs::create_directories(proc);
write_rule_file(rules / "test.yar");
const auto config = root / "model.conf";
{
std::ofstream out(config);
out << "db_path=" << (root / "model.db").string() << '\n'
<< "yara_rules_path=" << rules.string() << '\n'
<< "model_dir=" << models.string() << '\n'
<< "control_socket_path=\nenable_bpf_monitoring=false\nretro_hunt=false\nprivacy_trackers=false\n";
}
set_env_var("STRAWBERRY_PROCFS_ROOT", proc.string());
auto model = strawberry::learn::Model::initialized(strawberry::learn::ModelShape{}, 1);
model.generation = 123;
std::string error;
assert(strawberry::learn::save_model(models.string(), "shadow.sbm", model, error));
strawberry::StrawberryDaemon daemon;
int runs = 0;
const auto check = [&](bool acting, bool bad_promoted) {
assert(daemon.initialize(config.string()));
bool observed = false;
daemon.run([&] {
const auto status = nlohmann::json::parse(daemon.status_json());
const auto& m = status.at("model");
// Saved at the previous stop, restored at this start.
const auto& rarity = m.at("rarity_state");
assert(rarity.at("restored") == (runs > 0));
assert(rarity.at("load_error").get<std::string>().empty());
assert(m.at("shadow_active") == true);
assert(m.at("acting") == acting);
assert(m.at("promoted_generation") == (acting ? 123 : 0));
assert(m.at("promoted_error").get<std::string>().empty() == !bad_promoted);
assert(m.at("executor").at("submitted") == 0);
assert(status.at("timings").contains("model_inspection"));
// Tracker attribution: advisory status, listener off without OpenSnitch.
assert(status.at("privacy").at("strength") == "circumstantial");
assert(status.at("privacy").at("listener").at("listening") == false);
observed = true;
return false;
});
assert(observed && !daemon.is_running());
assert(fs::exists(models / "rarity.state"));
++runs;
};
check(false, false); // candidate alone cannot act
assert(strawberry::learn::save_model(models.string(), "promoted.sbm", model, error));
check(false, true); // legacy promotion did not evaluate executable actions
model.note = strawberry::learn::execution_approval("efficient");
assert(strawberry::learn::save_model(models.string(), "promoted.sbm", model, error));
check(false, true); // the gate must use this daemon's scan-profile budget
model.note = strawberry::learn::execution_approval("balanced");
assert(strawberry::learn::save_model(models.string(), "promoted.sbm", model, error));
check(true, false); // restarting the same daemon reloads both roles
write_binary_file(models / "promoted.sbm", "corrupt");
check(false, true);
assert(strawberry::learn::save_model(models.string(), "promoted.sbm", model, error));
fs::permissions(models / "promoted.sbm", fs::perms::group_write, fs::perm_options::add);
check(false, true);
unset_env_var("STRAWBERRY_PROCFS_ROOT");
std::error_code ec;
fs::remove_all(root, ec);
std::cout << " model loading/restart/fail-closed: PASSED\n";
}
#endif
} // namespace
int main() {
std::cout << "Running StrawberryDaemon tests..." << std::endl << std::endl;
#if !STRAWBERRY_HAVE_YARA
std::cout << "SKIP: daemon runtime test requires libyara" << std::endl;
return 0;
#else
test_daemon_procfs_event_persists_match();
test_daemon_opensnitch_containment();
test_model_loading_and_restart();
std::cout << std::endl << "All tests passed!" << std::endl;
return 0;
#endif
}