assay-cli 5.3.0

Policy-as-code gate for MCP agent tool calls, with verifiable evidence and Linux kernel enforcement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#[cfg(target_os = "linux")]
use crate::cli::commands::monitor::MonitorArgs;

#[cfg(target_os = "linux")]
pub(crate) fn out(message: impl AsRef<str>) {
    println!("{}", message.as_ref());
}

pub(crate) fn err(message: impl AsRef<str>) {
    eprintln!("{}", message.as_ref());
}

#[cfg(any(target_os = "linux", test))]
pub(crate) fn decode_utf8_cstr(data: &[u8]) -> String {
    let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
    String::from_utf8_lossy(&data[..end]).to_string()
}

#[cfg(any(target_os = "linux", test))]
pub(crate) fn dump_prefix_hex(data: &[u8], n: usize) -> String {
    data.iter()
        .take(n)
        .map(|b| format!("{:02x}", b))
        .collect::<Vec<_>>()
        .join("")
}

#[cfg(any(target_os = "linux", test))]
pub(crate) fn format_send_observation_summary(
    stats: &assay_monitor::MonitorStatsSnapshot,
) -> String {
    format!(
        "  • Send observation:   sendto emitted={} dropped={} no_peer={} non_ip={}; sendmsg emitted={} dropped={} no_peer={} non_ip={}",
        stats.sendto_events_emitted,
        stats.sendto_ringbuf_dropped,
        stats.sendto_no_peer,
        stats.sendto_non_ip_family,
        stats.sendmsg_events_emitted,
        stats.sendmsg_ringbuf_dropped,
        stats.sendmsg_no_peer,
        stats.sendmsg_non_ip_family
    )
}

#[cfg(any(target_os = "linux", test))]
pub(crate) fn decode_file_blocked_payload(data: &[u8]) -> Option<(u64, u64, u64, u32)> {
    if data.len() < 28 {
        return None;
    }

    let dev = u64::from_ne_bytes(data[0..8].try_into().ok()?);
    let ino = u64::from_ne_bytes(data[8..16].try_into().ok()?);
    let cgroup_id = u64::from_ne_bytes(data[16..24].try_into().ok()?);
    let rule_id = u32::from_ne_bytes(data[24..28].try_into().ok()?);

    Some((dev, ino, cgroup_id, rule_id))
}

/// Decode a type-20 (`EVENT_CONNECT_BLOCKED`) payload into the fields the live
/// view renders: `(cgroup_id, destination, port, rule_id)`.
///
/// Thin adapter over [`assay_monitor::events::decode_blocked_socket_payload`], the
/// single decode surface shared with the runner evidence exporter, so the byte
/// layout lives in exactly one place next to the projection that writes it.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn decode_blocked_net_payload(data: &[u8]) -> Option<(u64, String, u16, u32)> {
    let decoded = assay_monitor::events::decode_blocked_socket_payload(data)?;
    Some((
        decoded.cgroup_id,
        decoded.destination,
        decoded.port,
        decoded.rule_id,
    ))
}

#[cfg(target_os = "linux")]
pub(crate) fn log_violation(pid: u32, rule_id: &str, quiet: bool) {
    if !quiet {
        println!(
            "[PID {}] 🚨 VIOLATION: Rule '{}' matched file access",
            pid, rule_id
        );
    }
}

#[cfg(target_os = "linux")]
pub(crate) fn log_kill(
    pid: u32,
    mode: &assay_core::mcp::runtime_features::KillMode,
    grace: u64,
    quiet: bool,
) {
    if !quiet {
        println!(
            "[PID {}] 💀 INIT KILL (mode={:?}, grace={}ms)",
            pid, mode, grace
        );
    }
}

/// Format a monitor event into its human-readable line, or `None` when the event type produces no
/// output. Pure and platform-independent so the line shapes can be pinned by a unit test;
/// `log_monitor_event` is the thin stdout wrapper used on the live (Linux) capture path. These
/// formats are a producer contract: Plimsoll's capture scraper parses these exact shapes.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn format_monitor_event(event_type: u32, pid: u32, data: &[u8]) -> Option<String> {
    use assay_common::{
        EVENT_CONNECT, EVENT_FILE_BLOCKED, EVENT_OPENAT, EVENT_SENDMSG, EVENT_SENDTO,
    };

    // The live path always passes a full fixed-size event payload, but the slice contract is also
    // exercised by unit tests, so read fixed offsets with checked access and a zero fallback rather
    // than indexing, which would panic on a short buffer.
    fn read_u64(data: &[u8], start: usize) -> u64 {
        data.get(start..start + 8)
            .and_then(|s| <[u8; 8]>::try_from(s).ok())
            .map(u64::from_ne_bytes)
            .unwrap_or(0)
    }
    fn read_u32(data: &[u8], start: usize) -> u32 {
        data.get(start..start + 4)
            .and_then(|s| <[u8; 4]>::try_from(s).ok())
            .map(u32::from_ne_bytes)
            .unwrap_or(0)
    }

    let line = match event_type {
        EVENT_OPENAT => format!("[PID {}] openat: {}", pid, decode_utf8_cstr(data)),
        // Render the endpoint a reader is looking for. The raw form is unreadable in practice:
        // it requires knowing that 0200 is AF_INET and that the next two bytes are a
        // network-order port, and grepping a log for a decimal port against a hex payload
        // silently finds nothing. That produced three false negatives while measuring egress
        // coverage, each of which read like the monitor was blind.
        //
        // Reuses the decoder that already owns this rule. Note it is NOT the same layout as
        // decode_blocked_socket_payload, which reads the projected payload the cgroup hook
        // writes from the kernel's own bpf_sock_addr; these are the raw bytes the process
        // passed to connect(2). Display only: the peer set that grounds a refutation still
        // comes from cgroup events alone, for the reason `observed_peer` documents.
        EVENT_CONNECT => match assay_monitor::events::decode_connect_sockaddr(data) {
            Some(dest) => format!("[PID {pid}] connect: {}", dest.endpoint()),
            None => format!(
                "[PID {}] connect sockaddr[0..32]=0x{}",
                pid,
                dump_prefix_hex(data, 32)
            ),
        },
        EVENT_SENDTO | EVENT_SENDMSG => {
            let operation = if event_type == EVENT_SENDTO {
                "sendto"
            } else {
                "sendmsg"
            };
            match assay_monitor::events::decode_connect_sockaddr(data) {
                Some(dest) => format!("[PID {pid}] {operation}: {}", dest.endpoint()),
                None => format!(
                    "[PID {pid}] {operation} sockaddr[0..32]=0x{}",
                    dump_prefix_hex(data, 32)
                ),
            }
        }
        EVENT_FILE_BLOCKED => match decode_file_blocked_payload(data) {
            Some((dev, ino, cgroup_id, rule_id)) => format!(
                "[PID {}] 🛡️ BLOCKED FILE: dev={} ino={} cgroup={} rule_id={}",
                pid, dev, ino, cgroup_id, rule_id
            ),
            None => format!(
                "[PID {}] 🛡️ BLOCKED FILE: 0x{}",
                pid,
                dump_prefix_hex(data, 32)
            ),
        },
        11 => format!("[PID {}] 🟢 ALLOWED FILE: {}", pid, decode_utf8_cstr(data)),
        20 => match decode_blocked_net_payload(data) {
            Some((cgroup_id, dst, port, rule_id)) => format!(
                "[PID {}] 🛡️ BLOCKED NET: dst={} port={} cgroup={} rule_id={}",
                pid, dst, port, cgroup_id, rule_id
            ),
            None => format!(
                "[PID {}] 🛡️ BLOCKED NET : {}",
                pid,
                dump_prefix_hex(data, 20)
            ),
        },
        112 => {
            let dev = read_u64(data, 0);
            let ino = read_u64(data, 8);
            let gen = read_u32(data, 16);
            format!(
                "[PID {}] 🔒 INODE RESOLVED: dev={} (0x{:x}) ino={} gen={}",
                pid, dev, dev, ino, gen
            )
        }
        101..=104 => {
            let chunk_idx = event_type - 101;
            let start_offset = chunk_idx * 64;
            let dump = dump_prefix_hex(data, 64);
            format!(
                "[PID {}] 🔍 STRUCT DUMP Part {} (Offset {}-{}): {}",
                pid,
                chunk_idx + 1,
                start_offset,
                start_offset + 64,
                dump
            )
        }
        105 => {
            let path = decode_utf8_cstr(data);
            format!("[PID {}] 📂 FILE OPEN (Manual Resolution): {}", pid, path)
        }
        106 => format!("[PID {}] 🐛 DEBUG: Dentry Pointer NULL", pid),
        107 => format!("[PID {}] 🐛 DEBUG: Name Pointer NULL", pid),
        108 => format!(
            "[PID {}] 🐛 DEBUG: LSM Hook Entry (MonitorAll={})",
            pid,
            data.first().copied().unwrap_or(0)
        ),
        109 => format!("[PID {}] 🐛 DEBUG: Passed Monitor Check", pid),
        110 => {
            let ptr = read_u64(data, 0);
            format!("[PID {}] 🐛 DEBUG: Read Dentry Ptr: {:#x}", pid, ptr)
        }
        111 => {
            let ptr = read_u64(data, 0);
            format!("[PID {}] 🐛 DEBUG: Read Name Ptr: {:#x}", pid, ptr)
        }
        _ => return None,
    };
    Some(line)
}

#[cfg(target_os = "linux")]
pub(crate) fn log_monitor_event(event: &assay_common::MonitorEvent, args: &MonitorArgs) {
    if args.quiet {
        return;
    }
    if let Some(line) = format_monitor_event(event.event_type, event.pid, &event.data) {
        out(line);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        decode_blocked_net_payload, decode_file_blocked_payload, format_monitor_event,
        format_send_observation_summary,
    };
    use assay_common::{EVENT_CONNECT, EVENT_FILE_BLOCKED, EVENT_OPENAT};

    #[test]
    fn decode_file_blocked_payload_reads_binary_layout() {
        let mut data = [0u8; 32];
        data[0..8].copy_from_slice(&42u64.to_ne_bytes());
        data[8..16].copy_from_slice(&7u64.to_ne_bytes());
        data[16..24].copy_from_slice(&99u64.to_ne_bytes());
        data[24..28].copy_from_slice(&1234u32.to_ne_bytes());

        let decoded = decode_file_blocked_payload(&data).expect("payload should decode");
        assert_eq!(decoded, (42, 7, 99, 1234));
    }

    #[test]
    fn decode_blocked_net_payload_reads_binary_layout() {
        let mut data = [0u8; 40];
        data[0..8].copy_from_slice(&42u64.to_ne_bytes());
        data[8..10].copy_from_slice(&2u16.to_ne_bytes());
        data[10..12].copy_from_slice(&443u16.to_ne_bytes());
        data[12..16].copy_from_slice(&[203, 0, 113, 7]);
        data[32..36].copy_from_slice(&9u32.to_ne_bytes());

        let decoded = decode_blocked_net_payload(&data).expect("payload should decode");

        assert_eq!(decoded, (42, "203.0.113.7".to_string(), 443, 9));
    }

    // The line shapes below are the producer contract that Plimsoll's capture scraper parses (see
    // plimsoll src/plimsoll/capture.py parse_monitor_lines). openat and connect are the two the
    // scraper extracts, so they are pinned in full; the rest pin the structural payload layout.
    fn cstr(s: &str) -> Vec<u8> {
        let mut v = s.as_bytes().to_vec();
        v.push(0);
        v
    }

    #[test]
    fn openat_event_formats_exact_path_line() {
        let line = format_monitor_event(EVENT_OPENAT, 4242, &cstr("/etc/passwd")).unwrap();
        assert_eq!(line, "[PID 4242] openat: /etc/passwd");
    }

    #[test]
    fn connect_event_formats_exact_sockaddr_hex_line() {
        // Fallback: 4 bytes is too short to carry an address, so the decoder declines and the
        // raw form is printed rather than a confident decode of bytes we did not understand.
        let line = format_monitor_event(EVENT_CONNECT, 4242, &[0x02, 0x00, 0x00, 0x50]).unwrap();
        assert_eq!(line, "[PID 4242] connect sockaddr[0..32]=0x02000050");
    }

    #[test]
    fn send_events_format_explicit_destination() {
        let mut sockaddr = [0_u8; 16];
        sockaddr[0..2].copy_from_slice(&2_u16.to_ne_bytes());
        sockaddr[2..4].copy_from_slice(&9103_u16.to_be_bytes());
        sockaddr[4..8].copy_from_slice(&[127, 0, 0, 1]);

        assert_eq!(
            format_monitor_event(assay_common::EVENT_SENDTO, 42, &sockaddr).as_deref(),
            Some("[PID 42] sendto: 127.0.0.1:9103")
        );
        assert_eq!(
            format_monitor_event(assay_common::EVENT_SENDMSG, 43, &sockaddr).as_deref(),
            Some("[PID 43] sendmsg: 127.0.0.1:9103")
        );
    }

    #[test]
    fn send_event_formats_exact_sockaddr_hex_fallback() {
        let data = [0x02, 0x00, 0x00, 0x50];

        assert_eq!(
            format_monitor_event(assay_common::EVENT_SENDTO, 42, &data).as_deref(),
            Some("[PID 42] sendto sockaddr[0..32]=0x02000050")
        );
        assert_eq!(
            format_monitor_event(assay_common::EVENT_SENDMSG, 43, &data).as_deref(),
            Some("[PID 43] sendmsg sockaddr[0..32]=0x02000050")
        );
    }

    #[test]
    fn send_summary_exposes_per_hook_honesty_counters() {
        let stats = assay_monitor::MonitorStatsSnapshot {
            sendto_events_emitted: 1,
            sendto_ringbuf_dropped: 2,
            sendmsg_events_emitted: 3,
            sendmsg_ringbuf_dropped: 4,
            sendto_no_peer: 5,
            sendmsg_no_peer: 6,
            sendto_non_ip_family: 7,
            sendmsg_non_ip_family: 8,
            ..Default::default()
        };
        assert_eq!(
            format_send_observation_summary(&stats),
            "  • Send observation:   sendto emitted=1 dropped=2 no_peer=5 non_ip=7; sendmsg emitted=3 dropped=4 no_peer=6 non_ip=8"
        );
    }

    /// The exact 32 bytes an `EVENT_CONNECT` carried on `assay-bpf-runner` (kernel 6.8,
    /// aarch64) for a `connect(2)` to 127.0.0.1:9102, captured from a live run rather than
    /// constructed. Pins the rendered line a reader actually sees.
    #[test]
    fn connect_event_renders_decoded_endpoint() {
        let observed: [u8; 32] = [
            0x02, 0x00, 0x23, 0x8e, 0x7f, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        let line = format_monitor_event(EVENT_CONNECT, 4242, &observed).unwrap();
        assert_eq!(line, "[PID 4242] connect: 127.0.0.1:9102");
    }

    #[test]
    fn connect_event_port_is_not_read_host_order() {
        // 0x238e is 9102 big-endian and 36387 little-endian. Reading it host-order would look
        // entirely plausible in a log, which is why it is asserted against explicitly.
        let observed: [u8; 8] = [0x02, 0x00, 0x23, 0x8e, 0x7f, 0x00, 0x00, 0x01];
        let line = format_monitor_event(EVENT_CONNECT, 1, &observed).unwrap();
        assert!(line.ends_with(":9102"), "got {line}");
        assert!(!line.contains("36387"), "port read host-order: {line}");
    }

    #[test]
    fn file_blocked_event_formats_decoded_payload() {
        let mut data = [0u8; 32];
        data[0..8].copy_from_slice(&1u64.to_ne_bytes());
        data[8..16].copy_from_slice(&2u64.to_ne_bytes());
        data[16..24].copy_from_slice(&3u64.to_ne_bytes());
        data[24..28].copy_from_slice(&4u32.to_ne_bytes());
        let line = format_monitor_event(EVENT_FILE_BLOCKED, 4242, &data).unwrap();
        assert!(line.starts_with("[PID 4242] "), "{line}");
        assert!(
            line.ends_with(" BLOCKED FILE: dev=1 ino=2 cgroup=3 rule_id=4"),
            "{line}"
        );
    }

    #[test]
    fn blocked_net_event_formats_decoded_payload() {
        let mut data = [0u8; 40];
        data[0..8].copy_from_slice(&42u64.to_ne_bytes());
        data[8..10].copy_from_slice(&2u16.to_ne_bytes());
        data[10..12].copy_from_slice(&443u16.to_ne_bytes());
        data[12..16].copy_from_slice(&u32::from_ne_bytes([203, 0, 113, 7]).to_ne_bytes());
        data[32..36].copy_from_slice(&9u32.to_ne_bytes());

        let line = format_monitor_event(20, 4242, &data).unwrap();

        assert!(line.starts_with("[PID 4242] "), "{line}");
        assert!(
            line.ends_with(" BLOCKED NET: dst=203.0.113.7 port=443 cgroup=42 rule_id=9"),
            "{line}"
        );
    }

    #[test]
    fn allowed_file_event_formats_path_suffix() {
        let line = format_monitor_event(11, 4242, &cstr("/allowed/path")).unwrap();
        assert!(line.starts_with("[PID 4242] "), "{line}");
        assert!(line.ends_with(" ALLOWED FILE: /allowed/path"), "{line}");
    }

    #[test]
    fn unknown_event_type_produces_no_line() {
        assert_eq!(format_monitor_event(999, 4242, &[]), None);
    }

    #[test]
    fn short_buffers_do_not_panic_in_indexed_arms() {
        // The slice contract must stay bounds-safe: event types that read fixed offsets fall back
        // to zero on a short buffer instead of panicking (the live path always passes a full one).
        for event_type in [108u32, 110, 111, 112] {
            let line = format_monitor_event(event_type, 7, &[]).unwrap();
            assert!(line.starts_with("[PID 7] "), "{line}");
        }
    }
}