ptuf 0.5.0

PreToolUseFilter: a generic guardrail layer for coding agents
Documentation
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! In-memory representation of one audit log entry.
//!
//! `AuditRecord` mirrors the JSON schema in `docs/design/audit.md:14-46`.
//! `severity` is serialised as the lowercase enum spelling
//! (`info` / `low` / `medium` / `high` / `critical`).
//!
//! `schemaVersion` is always emitted (currently `1`) so JSONL consumers
//! can negotiate forward-compatible parsers. `agent` (e.g. `claude-code`),
//! `pluginVersions` (`name@version`), and `allowlistId` (only when an
//! `Allow` decision came from a non-expired allowlist hit) are populated
//! by the engine layer.

use std::path::Path;
use std::time::SystemTime;

use serde::Serialize;

use super::time as audit_time;
use crate::Decision;
use crate::config::Mode;
use crate::decision::Severity;
use crate::hook_input::HookInput;

/// Schema version of the audit record. Bumped only on incompatible
/// changes; additive fields keep version `1`.
pub const AUDIT_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AuditRecord {
    #[serde(rename = "schemaVersion")]
    pub schema_version: u32,
    pub timestamp: String,
    pub event: &'static str,
    pub tool: String,
    pub decision: &'static str,
    #[serde(rename = "ruleId", skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<&'static str>,
    #[serde(rename = "commandRedacted")]
    pub command_redacted: String,
    #[serde(rename = "projectRoot", skip_serializing_if = "Option::is_none")]
    pub project_root: Option<String>,
    pub mode: &'static str,
    /// `true` when the engine demoted a `Deny` decision to `Monitor`
    /// because the policy mode was `monitor`.
    #[serde(rename = "modeDemoted", skip_serializing_if = "is_false")]
    pub mode_demoted: bool,
    /// Allowlist `id` whose suppression turned a would-be Deny / Ask /
    /// Monitor into an `Allow`. Only set on `Allow` outcomes; `None`
    /// otherwise. When multiple allowlist entries hit, the first one
    /// wins (insertion order from the merged config).
    #[serde(rename = "allowlistId", skip_serializing_if = "Option::is_none")]
    pub allowlist_id: Option<String>,
    /// Adapter that produced the decision (`claude-code` / `cli`).
    /// `unknown` for direct library callers that never configured one.
    pub agent: &'static str,
    /// `name@version` for every loaded plugin in load order. Empty
    /// vec is omitted from the serialised form.
    #[serde(rename = "pluginVersions", skip_serializing_if = "Vec::is_empty")]
    pub plugin_versions: Vec<String>,
}

fn is_false(b: &bool) -> bool {
    !*b
}

impl AuditRecord {
    /// Build an `AuditRecord` for the supplied decision/input pair.
    /// The caller is responsible for redacting `command_redacted`
    /// before the record reaches the sink — keeping the redactor
    /// outside this constructor lets tests inject untouched commands
    /// and check the writer/sink in isolation.
    ///
    /// `agent` should be a stable adapter name (`claude-code` / `cli`);
    /// use `"unknown"` for embedded library callers that have not
    /// configured one. `plugin_versions` is the engine's
    /// cached `name@version` list; an empty vec is omitted from JSON.
    /// `allowlist_id` should be `Some` only on `Allow` outcomes that
    /// were produced by a non-expired allowlist hit.
    #[expect(
        clippy::too_many_arguments,
        reason = "constructor mirrors the audit JSON schema; collapsing into a builder \
                  struct is tracked separately"
    )]
    pub fn build(
        timestamp: SystemTime,
        decision: &Decision,
        mode: Mode,
        mode_demoted: bool,
        input: &HookInput,
        project_root: Option<&Path>,
        severity: Option<Severity>,
        command_redacted: String,
        allowlist_id: Option<String>,
        agent: &'static str,
        plugin_versions: Vec<String>,
    ) -> Self {
        let rule_id = decision.rule_id().map(str::to_owned);
        Self {
            schema_version: AUDIT_SCHEMA_VERSION,
            timestamp: audit_time::rfc3339_utc(timestamp),
            event: "PreToolUse",
            tool: input.tool_name.clone(),
            decision: decision_label(decision),
            rule_id,
            severity: severity.map(severity_label),
            command_redacted,
            project_root: project_root.and_then(|p| p.to_str().map(str::to_owned)),
            mode: mode_label(mode),
            mode_demoted,
            allowlist_id,
            agent,
            plugin_versions,
        }
    }
}

fn decision_label(decision: &Decision) -> &'static str {
    match decision {
        Decision::Allow => "allow",
        Decision::Monitor { .. } => "monitor",
        Decision::Ask { .. } => "ask",
        Decision::Deny { .. } => "deny",
    }
}

fn mode_label(mode: Mode) -> &'static str {
    match mode {
        Mode::Enforce => "enforce",
        Mode::Monitor => "monitor",
    }
}

fn severity_label(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => "info",
        Severity::Low => "low",
        Severity::Medium => "medium",
        Severity::High => "high",
        Severity::Critical => "critical",
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use serde_json::json;
    use std::path::PathBuf;
    use std::time::{Duration, UNIX_EPOCH};

    fn input(tool: &str, cmd: &str) -> HookInput {
        HookInput {
            tool_name: tool.into(),
            tool_input: json!({ "command": cmd }),
        }
    }

    // `Duration::from_secs(1_704_067_200)` is a Unix timestamp (the
    // start of 2024 UTC), not a duration in hours; rewriting it as
    // `from_hours(473352)` would erase the calendar semantics that the
    // assertion below relies on.
    #[allow(
        unknown_lints,
        clippy::duration_suboptimal_units,
        reason = "value is a Unix timestamp expressed in seconds, not a duration; lint name varies across clippy versions"
    )]
    #[test]
    fn builds_deny_record_with_severity_and_rule_id() {
        let decision = Decision::Deny {
            rule_id: "r.x".into(),
            reason: "blocked".into(),
        };
        let r = AuditRecord::build(
            UNIX_EPOCH + Duration::from_secs(1_704_067_200),
            &decision,
            Mode::Enforce,
            false,
            &input("Bash", "ls"),
            Some(&PathBuf::from("/repo")),
            Some(Severity::Critical),
            "ls".into(),
            None,
            "claude-code",
            Vec::new(),
        );
        assert_eq!(r.schema_version, 1);
        assert_eq!(r.timestamp, "2024-01-01T00:00:00Z");
        assert_eq!(r.event, "PreToolUse");
        assert_eq!(r.tool, "Bash");
        assert_eq!(r.decision, "deny");
        assert_eq!(r.rule_id.as_deref(), Some("r.x"));
        assert_eq!(r.severity, Some("critical"));
        assert_eq!(r.command_redacted, "ls");
        assert_eq!(r.project_root.as_deref(), Some("/repo"));
        assert_eq!(r.mode, "enforce");
        assert!(!r.mode_demoted);
        assert!(r.allowlist_id.is_none());
        assert_eq!(r.agent, "claude-code");
        assert!(r.plugin_versions.is_empty());
    }

    #[test]
    fn allow_record_omits_rule_id_and_severity() {
        let r = AuditRecord::build(
            UNIX_EPOCH,
            &Decision::Allow,
            Mode::Enforce,
            false,
            &input("Bash", "ls"),
            None,
            None,
            "ls".into(),
            None,
            "cli",
            Vec::new(),
        );
        let json = serde_json::to_string(&r).unwrap();
        assert!(!json.contains("\"ruleId\""));
        assert!(!json.contains("\"severity\""));
        assert!(!json.contains("\"projectRoot\""));
        assert!(!json.contains("\"modeDemoted\""));
        assert!(!json.contains("\"allowlistId\""));
        assert!(!json.contains("\"pluginVersions\""));
        assert!(json.contains("\"schemaVersion\":1"));
        assert!(json.contains("\"agent\":\"cli\""));
        assert!(json.contains("\"decision\":\"allow\""));
    }

    #[test]
    fn monitor_demote_flag_serialises_when_true() {
        let r = AuditRecord::build(
            UNIX_EPOCH,
            &Decision::Monitor {
                rule_id: "r".into(),
            },
            Mode::Monitor,
            true,
            &input("Bash", "ls"),
            None,
            Some(Severity::High),
            "ls".into(),
            None,
            "claude-code",
            Vec::new(),
        );
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"modeDemoted\":true"));
        assert!(json.contains("\"mode\":\"monitor\""));
    }

    #[test]
    fn ask_decision_serialises_as_ask_label() {
        let r = AuditRecord::build(
            UNIX_EPOCH,
            &Decision::Ask {
                rule_id: "r".into(),
                reason: "?".into(),
            },
            Mode::Enforce,
            false,
            &input("Bash", "ls"),
            None,
            Some(Severity::Medium),
            "ls".into(),
            None,
            "claude-code",
            Vec::new(),
        );
        assert_eq!(r.decision, "ask");
        assert_eq!(r.severity, Some("medium"));
    }

    #[test]
    fn allowlist_id_is_serialised_when_set() {
        let r = AuditRecord::build(
            UNIX_EPOCH,
            &Decision::Allow,
            Mode::Enforce,
            false,
            &input("Bash", "ls"),
            None,
            None,
            "ls".into(),
            Some("approved-hotfix".into()),
            "claude-code",
            Vec::new(),
        );
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"allowlistId\":\"approved-hotfix\""));
    }

    #[test]
    fn plugin_versions_serialise_as_name_at_version_list() {
        let r = AuditRecord::build(
            UNIX_EPOCH,
            &Decision::Allow,
            Mode::Enforce,
            false,
            &input("Bash", "ls"),
            None,
            None,
            "ls".into(),
            None,
            "cli",
            vec!["acme.security@0.1.0".into(), "core.demo@1.2.3".into()],
        );
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"pluginVersions\":[\"acme.security@0.1.0\",\"core.demo@1.2.3\"]"));
    }

    #[test]
    fn agent_label_is_always_serialised() {
        let r = AuditRecord::build(
            UNIX_EPOCH,
            &Decision::Allow,
            Mode::Enforce,
            false,
            &input("Bash", "ls"),
            None,
            None,
            "ls".into(),
            None,
            "claude-code",
            Vec::new(),
        );
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"agent\":\"claude-code\""));
    }

    #[test]
    fn severity_label_covers_each_variant() {
        assert_eq!(severity_label(Severity::Info), "info");
        assert_eq!(severity_label(Severity::Low), "low");
        assert_eq!(severity_label(Severity::Medium), "medium");
        assert_eq!(severity_label(Severity::High), "high");
        assert_eq!(severity_label(Severity::Critical), "critical");
    }

    use crate::testing::proptest::{decision, mode, richer_hook_input, severity};
    use proptest::option;
    use proptest::prelude::*;

    proptest! {
        // build() must complete without panicking on every combination of
        // Decision / Mode / Severity / HookInput shape we generate.
        #[test]
        fn pbt_build_never_panics(
            decision in decision(),
            mode in mode(),
            mode_demoted in any::<bool>(),
            input in richer_hook_input(),
            severity in option::of(severity()),
            cmd in "[ -~]{0,40}",
        ) {
            let _ = AuditRecord::build(
                UNIX_EPOCH,
                &decision,
                mode,
                mode_demoted,
                &input,
                None,
                severity,
                cmd,
                None,
                "unknown",
                Vec::new(),
            );
        }

        // The decision-label string is exactly one of the four documented
        // tags and matches the variant that produced it.
        #[test]
        fn pbt_decision_label_is_stable_and_exhaustive(d in decision()) {
            let label = decision_label(&d);
            prop_assert!(matches!(label, "allow" | "monitor" | "ask" | "deny"));
            let expected = match d {
                Decision::Allow => "allow",
                Decision::Monitor { .. } => "monitor",
                Decision::Ask { .. } => "ask",
                Decision::Deny { .. } => "deny",
            };
            prop_assert_eq!(label, expected);
        }

        // Mode label round-trips through the lowercase tag.
        #[test]
        fn pbt_mode_label_is_lowercase_tag(m in mode()) {
            let label = mode_label(m);
            prop_assert!(matches!(label, "enforce" | "monitor"));
            let expected = match m {
                Mode::Enforce => "enforce",
                Mode::Monitor => "monitor",
            };
            prop_assert_eq!(label, expected);
        }

        // Severity label round-trips through the lowercase tag.
        #[test]
        fn pbt_severity_label_is_lowercase_tag(s in severity()) {
            let label = severity_label(s);
            prop_assert!(matches!(label, "info" | "low" | "medium" | "high" | "critical"));
        }

        // The constructed record always carries the decision label of
        // the supplied decision and the tool name of the supplied input.
        #[test]
        fn pbt_record_mirrors_inputs(
            decision in decision(),
            mode in mode(),
            mode_demoted in any::<bool>(),
            input in richer_hook_input(),
            severity in option::of(severity()),
            cmd in "[ -~]{0,40}",
        ) {
            let r = AuditRecord::build(
                UNIX_EPOCH,
                &decision,
                mode,
                mode_demoted,
                &input,
                None,
                severity,
                cmd.clone(),
                None,
                "unknown",
                Vec::new(),
            );
            prop_assert_eq!(r.decision, decision_label(&decision));
            prop_assert_eq!(r.mode, mode_label(mode));
            prop_assert_eq!(&r.tool, &input.tool_name);
            prop_assert_eq!(r.command_redacted, cmd);
            prop_assert_eq!(r.event, "PreToolUse");
            prop_assert_eq!(r.mode_demoted, mode_demoted);
            // rule_id round-trips: only Allow has None.
            match decision {
                Decision::Allow => prop_assert!(r.rule_id.is_none()),
                _ => prop_assert!(r.rule_id.is_some()),
            }
        }

        // Serialising the record yields valid JSON containing the
        // documented top-level keys.
        #[test]
        fn pbt_record_serialises_to_object(
            decision in decision(),
            mode in mode(),
            mode_demoted in any::<bool>(),
            input in richer_hook_input(),
            severity in option::of(severity()),
            cmd in "[ -~]{0,40}",
        ) {
            let r = AuditRecord::build(
                UNIX_EPOCH,
                &decision,
                mode,
                mode_demoted,
                &input,
                None,
                severity,
                cmd,
                None,
                "unknown",
                Vec::new(),
            );
            let v = serde_json::to_value(&r).expect("serialise");
            let obj = v.as_object().expect("top-level object");
            for k in ["timestamp", "event", "tool", "decision", "commandRedacted", "mode"] {
                prop_assert!(obj.contains_key(k), "missing key {k}");
            }
        }
    }
}