strawberry/DEVELOPER.md
trvon a4179c474d
docs: say what the gate actually enforces, and what a passing verdict needs
The gate's own documentation claimed more than the tool did, in ways that
mattered once the integrity checks landed.

- "passes only if all 9 cells pass" was enforced by scripts, not by the gate; it
  is now enforced (previous commit) and the text says which criterion the tool
  applies: complete evidence, refused false, every pooled cell passing.
- The model digest proves agreement ACROSS reports. It cannot prove that the
  file on disk now is the one that was evaluated. Corrected everywhere.
- The remedy was described inconsistently: cutting the training bundles earlier
  is NOT enough (evaluation still replays the whole store), a bounded evaluation
  range is required. Written consistently, with --eval-after NS|auto.
- scripts/fleet_e2e.sh asserted three gate checks; promotion_gate emits five. It
  now asserts >= 5, requires the provenance fields, and adds the honest-evidence
  invariant: today every cell is in-sample, so at least one cell must report
  in_sample true, none may pass, and each must carry the out-of-sample failure.
  A pass over in-sample cells is itself a failure.
- The Salt/range runbooks advertised the flow as producing promotion evidence;
  it collects gate INPUT, and a passing verdict requires out-of-sample windows.
2026-11-19 17:30:35 -07:00

392 lines
30 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Developer Guide
## Architecture
Strawberry uses a **state machine** pattern with TinyFSM to manage daemon lifecycle:
```
┌─────┐ start ┌──────────┐ monitor ┌───────────┐
│Idle │────────→ │Initialize│─────────→ │Monitoring │
└─────┘ └──────────┘ └─────┬─────┘
│ update
↓
┌──────────┐
│Updating │
└─────┬────┘
│
↓
┌──────────┐
│Shutdown │
└──────────┘
```
## Code Structure
### Core Components
**State Machine** (`daemon_states.hpp/cpp`)
- Defines 5 states with type-safe transitions
- Events: StartEvent, MonitorEvent, UpdateRulesEvent, ScanEvent, StopEvent
**Process Monitor** (`process_monitor.hpp/cpp`, `bpf/process_monitor.bpf.c`)
- PIMPL pattern hides BPF implementation details
- libbpf backend hooks `execve` and `execveat` (fexecve/memfd) tracepoints; procfs polling is the fallback
- Every event is resolved through `/proc/<pid>/exe`: `executable_path` is what actually ran, `image_path` pins the inode for hashing/scanning, and `executable_deleted` / `executable_memfd` flag fileless or unlinked images
- Process identity: `make_process_node_id()` builds `process_<pid>_<boot8>_<starttime>` from `/proc/<pid>/stat` field 22 and the boot ID, so PID reuse does not merge unrelated processes (legacy `process_<pid>` when no start time is known)
- BPF timestamps use `CLOCK_BOOTTIME` and are converted to wall clock so both backends share one clock
- Both backends can emit a startup inventory of already-running processes
**YARA Scanner** (`yara_scanner.hpp/cpp`)
- Rule loading and compilation
- Staleness detection via timestamp tracking
- Multiple sources, each feed in its own namespace; file, fd and in-memory buffer scans; `/proc/<pid>/exe` scans
- `scan_process_memory(pid)` via `yr_rules_scan_proc` (needs `CAP_SYS_PTRACE`, or being the parent under yama `ptrace_scope` ≤ 1)
- `YaraMatch::severity` comes from `meta.severity`, else `meta.score` (≥90 critical, ≥70 high, ≥40 medium, else low)
**Detection Pipeline** (`detection_pipeline.hpp/cpp`)
- Refuses to start without compiled rules unless `require_rules=false`, and without a writable database
- Caches scan results by file identity (dev/inode/size/mtime/ctime) so repeated execs of the same binary are cheap. ctime is in the key because mtime is settable (`utimensat`): a rewrite that restores size and mtime (cp -p, install -p, package restore, a deliberate attacker) still changes ctime and is re-scanned instead of serving the old verdict. Cached size refusals stay unscanned and never trigger a fallback full-file hash; an already-known SHA remains available for IOC checks. The exec guard does not treat a cached size refusal as a YARA result: its own bounded scan/degradation policy still applies.
- Writes each event's nodes/edges/indicators in one transaction
- Heuristic indicators (`source=heuristic`): `MemfdExecution` (high) and `DeletedExecutable` (low)
- Correlation is batched (`run_pending_correlation()`, every ~2 s from the daemon loop, best-effort flush on shutdown). Final-flush exceptions are counted and recorded without allocation; resources still close, and startup rebuilds from persisted raw evidence. Ordinary evidence stays incremental; startup and explicit allowlist add/remove/maintenance requests rebuild from raw indicators and an immutable allowlist snapshot. An epoch rejects work invalidated during computation. Rebuilds upsert replacements before retiring unsupported findings of this engine in one view transaction, preserving history and other engines; failures roll back the view and schedule a full retry rather than losing consumed deltas. Large transactions retain the store's existing multi-block disk semantics (not a new crash-atomic snapshot guarantee).
- Immediate allowlist cleanup of this engine's findings checks complete actual indicator support with `(hash, path, rule)`, never a substituted IOC rule; missing or capped support is conservatively left for the rebuild. Cleared members cannot rejoin incremental outputs, while allowlist removal restores the retained raw evidence.
- Full persistence is shared by the daemon rebuild and `CorrelationEngine::correlate`, including the legacy offline correlate entrypoint, so typed-id migration cannot leave an old unqualified aggregate behind on the offline path. Standalone calls own a view transaction; calls inside an existing transaction do not commit or roll back the caller's work. The legacy CLI reads an immutable allowlist snapshot before opening a writer; missing policy means no allowlist, inaccessible/corrupt policy fails, and `PolicyStore::load_read_only` never seeds or migrates a policy. This is a read-only loader, not a capability restriction on later explicit mutation APIs.
- Shared-rule groups use `(source domain, namespace, rule name)`; demo normalizes to YARA. Legacy missing namespaces stay unknown and keep legacy YARA ids, but do not merge with known namespaces. Other ids encode typed length-prefixed fields. Metadata `rule_source`/`rule_namespace` makes the scope explicit; full rebuilds retire obsolete unqualified ids. Lineage/hash/rule counts distinguish stable process instances from numeric PIDs.
- IOC hash set (`ioc_set.hpp`) checked for every image → `IOC_KnownMalwareHash` (`source=ioc`); MD5 is computed from the same in-memory copy for OpenSnitch
- `assess_exec(fd, path)` serves the exec guard (reads the fanotify event fd, never reopens the path; hash-only when prevention is off, to enforce quarantines)
- `record_exec_decision`, `record_behavior`, `scan_process_memory` store `source=prevention|behavior|memory` evidence; memory scans use a separate scanner instance under their own mutex so slow scans never block exec decisions
- `set_detection_callback` reports stored detections to the daemon (auto-containment)
**Policy** (`policy.hpp/cpp`)
- `PolicyStore`: `policy.json` v2 (next to the DB) with feeds (kind `yara|hashes|domains|ips|nets`), allowlist, containment, quarantine, protection settings, history and `removed_defaults`; strict validation of control-socket payloads; `match()` used by the pipeline to suppress allowlisted detections; `generation()` bumps on every save (exec-guard cache key)
- Helpers shared by daemon/CLI/updater: `policy_path_for`, `feeds_dir_for`, `installed_feed_roots`, `read_feed_state`, `request_feed_update`
**Rule updater** (`rule_updater.hpp/cpp`, needs libcurl + libarchive)
- `update_feeds()` behind an injectable `Fetcher` (tests use a fake); GitHub release digest verification, safe extraction, compile check via `YaraScanner::check_rules`, atomic `current` switch, `state.json`, then `reload-rules`
- Run by `strawberry rules fetch` from `strawberry-update.service` (daily timer, path trigger); on macOS from `com.strawberry.update` as `_strawberry`
**OpenSnitch** (`opensnitch.hpp/cpp`)
- Detects the rules dir and `EnableChecksums`; writes only `strawberry-*.json` (0600, atomic); list rules (`lists.domains/ips/nets`) and per-binary containment rules (`process.path` + `process.hash.md5`); `is_protected_system_path()` is the shared never-auto-block check
**Exec guard** (`exec_guard.hpp/cpp`)
- fanotify `FAN_CLASS_CONTENT` + `FAN_OPEN_EXEC_PERM`, `FAN_MARK_FILESYSTEM` per local mount; reader thread, scan workers, deadline watchdog (fail open), each event answered exactly once; verdict cache keyed by dev/ino/size/mtime/ctime + generation; own-pid bypass
- `decide_exec()` is the pure verdict function (unit-tested): quarantine → block in any mode; allowlist → allow; system path → would-block only; enforce/audit otherwise
**Behavior** (`behavior_engine.hpp/cpp`, `file_watch.hpp/cpp`)
- eBPF `behavior_events` ring buffer: `connect` (AF_INET/6), `ptrace` attach/seize, `init_module`/`finit_module`
- `FileWatcher`: fanotify `FAN_REPORT_DFID_NAME` over persistence and drop directories (needs file handles; not overlayfs)
- `BehaviorEngine` rules with injected resolve/is_flagged/ioc_ip/emit: `IOC_Connection`, `FlaggedProcessNetwork`, `PtraceAttach`, `KernelModuleLoad`, `PersistenceWrite`, `DownloadThenExecute`; `resolve_process_ref(pid)` gives the stable node id of a live process
- `observe_process(info)` captures a stable exec/inventory identity before scan queueing, in bounded in-memory windows only. Ordinary connects add no procfs I/O. Network-to-write joins require that observed lifetime, a nonzero exec timestamp, and matching resolved writer node; connections predating its observation cannot be assigned to a reused PID. Unobserved/unknown/late identities are unjoined (a coverage limitation, not proof of benignity); direct IOC/flagged-network rules remain enabled. At most 8192 windows × 64 connections are retained, with single-window eviction rather than clear-all on churn.
**Daemon response** (`daemon_app.cpp`)
- Auto-containment from the detection callback; blocklist sync after reloads; exec guard lifecycle follows `prevention_mode` (and stays up while anything is quarantined)
- Response verbs: `quarantine`/`quarantine-remove` by hash (path from stored evidence), `scan-memory` and `process-suspend/resume/kill` by stable node id re-verified with `resolve_process_ref`, protected-process refusal list
- Background memory-scan queue (≤ 32, one at a time): memfd/deleted execs, ptrace targets, operator requests
**Inspection learning (Stage 4)** (`learn/`, `inspection_executor.hpp/cpp`)
- Offline MLP training, live shadow scoring and replay-gated operator promotion;
this is budgeted inspection selection, not AlphaZero tree search or an autonomous detector
- Promotion evidence must be out-of-sample. `model train`/`fleet train` record the
inclusive window range they trained on; every `replay --policy-eval` cell and every
pooled `fleet gate` cell publishes the model digest (`model_sha256`), that training
range, the evaluated range and `in_sample`, and `promotion_gate()` fails a cell whose
ranges overlap or whose model has no recorded range (unprovable, never assumed
out-of-sample). `fleet gate` additionally refuses a report set with a missing or
disagreeing digest and requires the complete 3 seeds x 3 periods matrix (`complete`,
`expected_cells`; an incomplete or mixed set yields no verdict). Digest agreement is
not file provenance: it only shows that the reports in one set judged the same bytes.
Cutting the training bundles earlier is not sufficient on its own, because the node
still replays its whole store; the evaluation itself has to be bounded
(`replay --policy-eval --eval-after NS|auto`; the replay-side bound and its refusal text are in
the tree, the CLI flag is landing in parallel - `API_CONTRACT.md`).
- Offline replay uses seeded, class-weighted positive/unlabeled sampling.
Positives reserve up to one fifth of the sample (at least one); negatives
borrow vacant slots but yield to later positives. `max_entity_share`
bounds each root program's combined positive + negative count. A capped
entity refreshes its own class reservoir across time instead of freezing
early examples. Capped refreshes do not dilute other entities' global
candidate counts. Cross-entity positive replacement can evict one negative
too, temporarily leaving the sample one short. Slot back-links use
swap-and-pop plus geometric shrinking/release of per-entity allocations,
with amortized O(1) mutations and allocated slot storage bounded by
`max_examples`. Debug invariants check capacity as well as logical size.
Entity counters last only while retained; the constrained
sample is **not** a uniform joint sample, and unlabeled is not proven benign.
- Replay joins final label judgments retrospectively in stored order, not as
point-in-time policy replay. An allowlist entry may cover many hashes;
removal retires all its bindings, without erasing other entries or idless
negatives. Retired-entry tombstones ignore delayed suppression observations;
only an explicit operator add reopens that id. Quarantine removal retracts
only operator quarantine provenance, not an independent same-text reason.
Retraction restores independent evidence; it never invents a positive.
Unreadable/malformed label evidence fails visibly. Resolver memory scales
with distinct evidence bindings/tombstones, **not** the example cap; a full
replay/training RSS bound still needs measurement.
- `replay --training-summary` is an opt-in, CLI-only aggregate view of the same
resolver and sampler, not a readiness engine or trainer. Ordinary replay keeps
collection disabled and adds `examples_collected` to JSON. The summary uses
fixed provenance/action buckets and five anonymous concentration counts;
metadata does not feed back into label resolution or admission. Effective
entity cap and positive quota come from the sampler's own helpers.
- `scan_store_read_only` retains best-effort record delivery for Database/app/MCP
and import callers, but reports skipped/invalid segments, listing/extent
availability, actual header status, torn tails, and per segment whether a block
could not be decoded (a zstd dictionary this build lacks, or out of memory) or
the scan stopped on a complete but invalid block header. Those two are counted
per segment because the aggregate tail error keeps only the last one. A
genuine short tail an active writer still owns stays tolerated; sealed footer
and manifest counts are only compared when every block decoded, so a missing
decoder is never reported as corrupt data. `replay_store` rejects
incomplete/corrupt inputs with an explicit failure category and **no usable
partial report/examples** (missing decoder → unavailable, complete invalid
header → invalid). This also tightens corrupt-input rejection for
offline trainer loader callers; no trainer algorithm/split/model format changes.
Ordinary replay retains valid fragment/fallback and active-tail support. The
summary additionally requires a current manifest, no torn tail, and matching
decoded manifest identity/generation and active extents before/after replay.
This is only a cooperative immutable-snapshot observation, not atomic capture
or a hostile-filesystem proof. It takes no writer lock and repairs nothing.
- Summary mode never uses daemon status to discover the input store: pass a
snapshot path or configure `db_path`. Its JSON is one aggregate document; human
output has no host identifiers. CLI-local `Histogram`/`ScopedTimer` (the
`PerfStats` primitives) and Tracy zones record replay and summary-build **wall
microseconds**, separately from deterministic semantics. They do not measure
CPU, RSS, or daemon timings. `store verify --json` now captures successful
config chatter; verifier `ok` can still coexist with skipped-coverage notes,
so it is not a substitute for the stricter replay loader.
- The telemetry writer owns `ShadowScorer`; separate shadow/promoted estimates,
bounded pending decisions/actions, and durable acting records before dispatch
- `InspectionExecutor` runs one bounded low-priority worker under `model_inspect`
admission. Memory jobs enter the existing queue behind rule/operator requests,
retaining stable process identity; deep rescans read paced bounded image copies
- Both paths recheck identity/protected processes. The model never directly invokes
exec prevention, containment or process actions. R10 forbids direct learning/response
dependency coupling outside the CLI/daemon orchestration translation units
- `contain-remove` emits no retraction label, so hash-carrying `contain-add`
positives persist in the replay join. `process-kill`/`process-suspend`
labels carry only a path and node id (no sha256), so they do not join by
hash at all; `process-resume` also emits no retraction label. These are
documented gaps, not silent reinterpretations.
- `model_shadow=false` disables both roles. Only models re-promoted under the
[execution-policy gate](docs/evaluation/stage4-execution-gate.md) may act; old
promotion files or a changed scan-profile budget require re-evaluation
- Hourly allocation is estimated cost, not measured CPU-time enforcement. Online
training, calibrated costs, subtree watching and Stage 5 detections remain future work
**Resource governor** (`resource_governor.hpp/cpp`, `thread_priority.hpp/cpp`)
- Governor thread (`governor_tick_ms`, default 1 s) samples own CPU (share of affinity/cgroup `cpu.max` capacity), RSS vs budget (profile, capped by cgroup `memory.max`), host PSI `some avg10` (loadavg fallback), `/proc/diskstats` utilization and `MemAvailable`. Host pressure is **fail-safe**: any one signal (CPU, I/O or memory PSI, or low `MemAvailable`) is enough to defer background work. `host.block_io_util_pct` is diagnostic telemetry only and never suppresses I/O PSI, because global PSI also counts waits with no block-device counter (FUSE/network-backed I/O, display page flips); an unknown/new/reset device or an oversized read reports unknown rather than a false idle value
- Level `normal/warning/critical/emergency` with hysteresis (escalate 500 ms; release 150 ms CPU / 1000 ms memory); host busy with a 0.75 release band, severe at 2× a threshold or MemAvailable < 5%
- `admit(WorkClass)`: exec guard always; exec scans deferred only at emergency; background classes deferred while busy/warning, never forced at critical, otherwise forced once per `background_max_deferral_s`
- `guard_should_degrade(bytes)`: hash/IOC/quarantine only for files over the profile cap or under pressure (profile-dependent); degraded results are not cached
- `pace_read(bytes)`: token bucket for background reads (halved under pressure), sleeps in ≤ 200 ms slices
- Parsers are pure functions; sampler, clock and sleeper are injectable (`tests/test_resource_governor.cpp`)
| Profile | pipeline / guard workers | read MB/s | max image / guard full scan | YARA timeout | memory scans | inventory | own CPU high | PSI cpu/io/mem | budget | priority |
|---|---|---|---|---|---|---|---|---|---|---|
| efficient | 1 / 1 | 16 | 64 / 16 MiB | 5 s | 10 s, queue 4 | 200 ms | 10% | 20/15/5 | 256 MiB | nice 19, io idle |
| balanced | 1 / 2 | 48 | 64 / 32 MiB | 10 s | 20 s, queue 8 | 50 ms | 25% | 40/30/10 | 768 MiB | nice 10, io be 7 |
| aggressive | 2 / 2 | ∞ | 256 / 64 MiB | 30 s | 30 s, queue 32 | none | 50% | 70/50/20 | 1 GiB | nice 0 |
**Profiling**
- `PerfStats` (`perf_stats.hpp`): lock-free log2 histograms (exec decision, exec assess, queue wait, image scan, YARA, image size, DB commit, correlation, rule compile, memory scan, model inspection) → status `timings`
- Tracy: `meson setup /var/tmp/profbd -Denable_profiling=true` builds the client from `third_party/tracy.wrap`, pinned to v0.15.0 = the Arch `tracy` tools (`tracy-capture`, `tracy-csvexport`, `tracy-profiler`): client and tools must match exactly, so bump both together. On-demand mode: nothing is recorded or paid for unless a capture is connected. Macros in `profiling.hpp` (`STRAWBERRY_ZONE`, `STRAWBERRY_PLOT`, `STRAWBERRY_THREAD_NAME`) are no-ops otherwise. Zones cover the daemon scan path (`assess_exec`, `scan_image`, `scan_on_demand`, `image.read`, `image.sha256`, `yara_scan`, `rule_compile`), correlation/db/governor/model, the tray (`tray.*`) and evidence reloads.
- Headless capture (no GUI, no root): `scripts/profile_capture.sh run OUT -- CMD...` or `attach OUT SECONDS` for a running profiled daemon/tray → `OUT.tracy`, `OUT.zones.csv` and a top-zones table. `strawberry-scan-bench --rules DIR FILE... | @list` (dev tool) runs the real `scan_on_demand` path over files with the real governor, e.g. `scripts/profile_capture.sh run /var/tmp/sb-prof/scan -- /var/tmp/profbd/tests/strawberry-scan-bench --rules packaging/rules-snapshot/yara-forge-core @list.txt`. Baseline 2026-11-14 (6 yams ASan binaries, 668 MiB, idle host): YARA 86%, read 9%, sha256 5%; ~61 MiB/s end to end; PT_LOAD segments are 35–48% of those files. libyara internals (perf with a symbol build of the same 4.5.8): `_yr_scanner_scan_mem_block` (Aho-Corasick walk) 59%, `yr_re_fast_exec` 14% + `yr_scan_verify_match` 10% (atom-hit verification), rule compile ~5%. Engine A/B (`strawberry-scan-bench --engine`, 3434 ELFs / 2.9 GB): fast mode 1.01x (not used), loaded segments only 1.11x (~2x on debug builds; opt-in `guard_loaded_segments_only`); a `-O3 -march=native` LTO libyara scans ~2.5% slower than Arch's `-O2` build (the walk is memory-bound), loads rules ~14% faster.
- Constrained-lane KPI: `make perf-kpi LABEL=x` runs the daemon with the installed YARA Forge rules in a privileged container capped at 2 CPUs / 2 GiB (startup inventory, idle, exec storm under CPU load, large binaries, rule reload) → `build/perf/<stamp>-x/kpi.json`; `scripts/perf_kpi_report.py --compare A B` budgets both the phase-end daemon RSS and the per-phase RSS peak against the baseline run, per phase: max(32 MB, 15%) of the last sample, max(64 MB, 15%) of the peak — a peak-only regression fails, and missing RSS samples fail closed.
**Rule partitions** (`rule_partition.hpp/cpp`, `YaraScanner`)
- Why: libyara verifies every atom hit and only checks a rule's `filesize` / header test at the end. YARA-X avoids that by disabling patterns of rules whose `filesize` bound or header constraint already fails (audit of its `search_for_patterns`, 2026-11-14) — that, not the language, is why it scanned ~1.6x faster. In the yara-forge pack 1787 rules require MZ and 2498 bound `filesize`, so for a big Linux ELF most verification is wasted.
- What: after each rules load a background thread splits the sources (lexer-aware; `include` or a rule-count mismatch vs libyara disables it), takes facts from TOP-LEVEL `and` terms only (`uint16(0)==0x5a4d`/`pe.is_pe` -> MZ, ELF/Mach-O magic, `filesize <`/`<=`), and compiles subsets per (MZ / non-MZ) x size bucket (<1, 1-4, 4-16, >=16 MiB). A rule is left out only when a term is provably false for every file in the partition; global rules and rules referenced by kept rules always stay. Subsets are built in priority order (big non-PE first) while their total rule count stays within `rule_partition_budget_pct` (100 = ~one extra full set: +59 MiB, 3 subsets); a subset keeping >= 90% of rules is skipped. File/buffer/fd scans pick the subset; process-memory scans use the full set. Compiled subsets are cached under `rules_cache_dir/partitions/<sig>/`.
- Measured (5132 rules): big ASan ELF 1.64x, 1200 system binaries 1.59x, 0 match differences (incl. 348 positive files across MZ/ELF/raw x small/5 MiB). Tests: `test_rule_partition` (splitter traps, facts, exclusion soundness, real pack = 5132 rules), `test_yara_scanner` differential (24 file shapes x memory/ranges/fd scans, every subset built), fail-closed; `strawberry-scan-bench --partitions` for real-pack A/B.
**Database** (`database.hpp/cpp`)
- Backed by the event store (`src/store/`): `<db_path>` is a directory with `MANIFEST`, `evidence/` and `telemetry/` zstd segments; queries come from an in-memory view rebuilt on open
- A legacy unqlite-format `database.db` file is imported on the first writer open and kept as `database.db.migrated-<ts>`
- Graph structures: GraphNode and GraphEdge
- Indicator storage with metadata
- Single writer enforced with `flock` on `<db>.lock`; `open_read_only()` for queries never writes back
- `begin_transaction()` / `commit_transaction()` batch writes into one persist
**Hash Utils** (`hash_utils.hpp/cpp`)
- SHA256 and MD5 implementations using OpenSSL
- File and buffer hashing support
**Config** (`config.hpp/cpp`)
- Simple key=value parser
- Default configuration values
## Building
`.clangd` points editor diagnostics at Meson's `builddir/compile_commands.json`;
configure the build before relying on C++ editor diagnostics. Docker validation
caps compilation and test parallelism at two jobs to fit its memory limit.
```bash
# Debug build
meson setup builddir --buildtype=debug
meson compile -C builddir
# Release build
meson setup builddir --buildtype=release
meson compile -C builddir
# With tests
meson setup builddir -Denable_tests=true
meson compile -C builddir
meson test -C builddir
```
## Design Patterns
**PIMPL (Pointer to Implementation)**
```cpp
class Component {
private:
class Impl;
std::unique_ptr<Impl> pimpl_;
};
```
Benefits: Hide implementation, reduce compilation dependencies
**State Machine**
```cpp
class MonitoringState : public DaemonState {
void react(ScanEvent const & event) override;
};
```
Benefits: Type-safe transitions, clear state flow
**Observer (Callbacks)**
```cpp
monitor->start([this](const ProcessInfo& info) {
this->handle_process(info);
});
```
Benefits: Decoupled components, flexible event handling
## Testing
Run tests:
```bash
meson test -C builddir --verbose
```
Add new tests to `tests/` directory following existing patterns.
Invariant (property) tests: `tests/test_invariants.cpp` checks properties
that must hold for every input on thousands of seeded random cases per run —
exec decisions (quarantine always blocks; allowlist, system paths and
non-enforce modes never auto-block; monotone in severity), histogram
percentiles, IOC network matching vs a brute-force reference, IOC list
normalization (bounded, valid, idempotent), governor parsers and admission,
and untrusted policy/status JSON. A failure prints the seed; reproduce with
`STRAWBERRY_PROPERTY_SEED=<seed> builddir/tests/test_invariants`.
Fuzzing (libFuzzer + ASan/UBSan, clang): `make fuzz` (or `FUZZ_SECONDS=300
make fuzz`) builds `fuzz/` in `build/fuzz` and runs each target in turn at
nice 19 with RSS/malloc caps. Targets cover every boundary that parses
untrusted input: `fuzz_ioc_list` (feed bodies, IOC set loading),
`fuzz_policy_apply` (control-socket payload verbs; accepted policy must
reload), `fuzz_governor_parsers` (/proc, PSI, cgroup), `fuzz_rule_partition`
(rule splitter, condition facts/identifiers, file partition choice),
`fuzz_status_snapshot`
(client-side status parsing), `fuzz_config`, `fuzz_mcp_handle` (agent
JSON-RPC, read-only). Seeds live in `fuzz/seeds/<target>`, corpora in
`build/fuzz-corpus`, crashes in `build/fuzz-artifacts`. Add a target for any
new parser of untrusted input.
Root-only tests (fanotify exec prevention + quarantine, eBPF behavior events,
persistence watcher, process-memory scan) skip when not root. Run them in a
privileged container:
```bash
make docker-live-tests # scripts/run_live_tests_docker.sh
```
## Platforms
Linux and macOS share one tree. Platform code sits behind `#if defined(__linux__)`
/ `#if defined(__APPLE__)`; a Linux branch is never changed to serve macOS.
| Piece | Linux | macOS |
| --- | --- | --- |
| Process facts | `/proc/<pid>/{exe,stat,cmdline}` | `include/strawberry/platform_process.hpp` (libproc, sysctl `KERN_PROC_PID`, `KERN_PROCARGS2`) |
| Process identity | start ticks + `boot_id` | start time (µs since epoch) + `kern.bootsessionuuid` |
| Exec events | eBPF (`src/bpf/`) or procfs polling | Endpoint Security or libproc polling (`process_monitor.cpp`) |
| Exec prevention | fanotify `FAN_OPEN_EXEC_PERM` | ES `AUTH_EXEC` (`exec_guard.cpp`) |
| File watch | fanotify `FAN_REPORT_DFID_NAME` | ES notify events, inverted target-path muting (`file_watch.cpp`) |
| Resource sampler | `/proc`, PSI, cgroup v2 | Mach `task_info`/`host_statistics64`, `getloadavg` (`resource_governor.cpp`) |
| Durable sync | `fdatasync` | `fcntl(F_FULLFSYNC)` (`sys_io.hpp`) |
| Peer credentials | `SO_PEERCRED` | `LOCAL_PEERCRED` + `LOCAL_PEERPID` |
| Service manager | systemd units (`scripts/*.service`) | launchd jobs (`packaging/macos/*.plist`) |
| Service hints in messages | `include/strawberry/service_hints.hpp` | same header, launchctl strings |
| System store | `/var/lib/strawberry` | `/var/db/strawberry` (`kSystemStorePath`) |
ES helpers are in `src/platform/es_support.hpp`. ES handlers are clang blocks
(`-fblocks`, added by the `enable_endpoint_security` meson option); every
handler is `noexcept` and records swallowed exceptions with
`STRAWBERRY_NOTE_SWALLOWED()`. Tests that pass a synthetic procfs root
(`STRAWBERRY_PROCFS_ROOT`) still use the procfs code on macOS.
Checks per platform:
- macOS: `make test`; root-only ES checks: `make macos-live-tests` (needs the
ES entitlement; ad hoc signing works only with SIP disabled).
- Linux: `make test`, `make docker-live-tests`, `make fuzz`.
## Remotes
`origin` fetches from GitHub and pushes to GitHub and Forgejo. GitHub runs
the macOS CI job; Forgejo skips it (`github.server_url` gate in
`.github/workflows/build.yml`).
```bash
git remote add origin git@github.com:trvon/strawberry.git
git remote set-url --add --push origin git@github.com:trvon/strawberry.git
git remote set-url --add --push origin ssh://git@git.trevon.dev:2222/trevon/strawberry.git
git remote add forgejo ssh://git@git.trevon.dev:2222/trevon/strawberry.git
```
## Contributing
1. Fork the repository
2. Create a feature branch
3. Write tests for new features
4. Ensure all tests pass
5. Submit pull request
### Code Style
- Use C++23 features appropriately
- Follow RAII for resource management
- Prefer `std::unique_ptr` over raw pointers
- Use const correctness
- Classes: PascalCase
- Functions: snake_case
- Members: snake_case_ (trailing underscore)
## Debugging
```bash
# GDB
gdb builddir/src/strawberry
(gdb) break main
(gdb) run config/strawberry.conf
# Valgrind
valgrind --leak-check=full builddir/src/strawberry
```
## Extending
### Adding a New State
1. Define state class in `daemon_states.hpp`
2. Implement `entry()` and event handlers
3. Add transitions in existing states
### Adding a Component
1. Create header in `include/strawberry/`
2. Use PIMPL pattern for implementation hiding
3. Add implementation in `src/`
4. Update `src/meson.build`