libverify-core 0.13.0

Platform-agnostic SDLC verification engine — evidence model, controls, assessment
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
use crate::control::{Control, ControlFinding, ControlId, builtin};
use crate::evidence::{EvidenceBundle, EvidenceState};

/// Patterns matched case-insensitively against agent action commands.
/// Users can extend via `AgentSpec.custom_destructive_patterns`.
pub const NOTABLE_COMMAND_PATTERNS: &[&str] = &[
    // Filesystem
    "rm -rf",
    "rm -r",
    "rm -fr",
    "shred ",
    "find / -delete",
    "find . -delete",
    // SQL
    "drop table",
    "drop database",
    "drop schema",
    "truncate table",
    "delete from",
    // Git history mutation
    "git push --force",
    "git push -f",
    "git reset --hard",
    "git push origin :",
    // Container/orchestration
    "kubectl delete",
    "kubectl drain",
    "helm uninstall",
    "helm delete",
    "docker rm",
    "docker system prune",
    "docker-compose down -v",
    // Infrastructure
    "terraform destroy",
    "pulumi destroy",
    // Cloud provider
    "aws s3 rm",
    "aws s3 rb",
    "aws ec2 terminate",
    "aws rds delete",
    "aws lambda delete",
    "gsutil rm",
    "gcloud compute instances delete",
    "az vm delete",
    "az storage blob delete",
    // System administration
    "chmod 000",
    "chmod -r 000",
    "iptables -f",
    "systemctl stop",
    "kill -9",
    "format c:",
];

/// Surfaces privileged operations from two evidence sources:
/// 1. Structured git events (force push, admin bypass, tag/branch deletion)
/// 2. Agent action log commands matched against notable patterns
///
/// This control does not enforce policy — it makes operations visible.
/// The OPA profile decides whether each finding is pass/review/fail.
pub struct PrivilegedOperationAuditControl;

impl Control for PrivilegedOperationAuditControl {
    fn id(&self) -> ControlId {
        builtin::id(builtin::PRIVILEGED_OPERATION_AUDIT)
    }

    fn description(&self) -> &'static str {
        "Privileged operations (force push, notable commands, admin bypass) must be audited"
    }

    fn evaluate(&self, evidence: &EvidenceBundle) -> Vec<ControlFinding> {
        let id = self.id();
        let mut subjects: Vec<String> = Vec::new();

        // --- Source 1: Structured git events ---
        let git_gaps = match &evidence.privileged_git_events {
            EvidenceState::Complete { value } => {
                for e in value {
                    let target = e
                        .branch
                        .as_deref()
                        .or(e.tag.as_deref())
                        .unwrap_or("unknown");
                    subjects.push(format!(
                        "{}: {} on {} by {}",
                        e.action.as_str(),
                        e.detail.as_deref().unwrap_or(""),
                        target,
                        e.actor
                    ));
                }
                false
            }
            EvidenceState::Partial { value, .. } => {
                for e in value {
                    let target = e
                        .branch
                        .as_deref()
                        .or(e.tag.as_deref())
                        .unwrap_or("unknown");
                    subjects.push(format!(
                        "{}: {} on {} by {}",
                        e.action.as_str(),
                        e.detail.as_deref().unwrap_or(""),
                        target,
                        e.actor
                    ));
                }
                true
            }
            EvidenceState::Missing { .. } | EvidenceState::NotApplicable => false,
        };

        // --- Source 2: Agent action log command patterns ---
        let action_gaps = match &evidence.agent_action_log {
            EvidenceState::Complete { value } | EvidenceState::Partial { value, .. } => {
                let custom_patterns: Vec<String> = match &evidence.agent_spec {
                    EvidenceState::Complete { value } | EvidenceState::Partial { value, .. } => {
                        value
                            .custom_destructive_patterns
                            .iter()
                            .map(|p| p.to_lowercase())
                            .collect()
                    }
                    _ => vec![],
                };

                for action in &value.actions {
                    let lower = action.command.to_lowercase();
                    let matched = NOTABLE_COMMAND_PATTERNS.iter().any(|p| lower.contains(p))
                        || custom_patterns.iter().any(|p| lower.contains(p.as_str()));
                    if matched {
                        subjects.push(format!("command: {}", action.command));
                    }
                }
                matches!(&evidence.agent_action_log, EvidenceState::Partial { .. })
            }
            EvidenceState::Missing { .. } | EvidenceState::NotApplicable => false,
        };

        // --- Both sources missing = Indeterminate ---
        let git_missing = matches!(
            evidence.privileged_git_events,
            EvidenceState::Missing { .. }
        );
        let log_missing = matches!(evidence.agent_action_log, EvidenceState::Missing { .. });
        let git_na = matches!(evidence.privileged_git_events, EvidenceState::NotApplicable);
        let log_na = matches!(evidence.agent_action_log, EvidenceState::NotApplicable);

        if git_na && log_na {
            return vec![ControlFinding::not_applicable(
                id,
                "No privileged operation evidence applicable",
            )];
        }

        if git_missing && log_missing {
            let mut gaps = vec![];
            if let EvidenceState::Missing { gaps: g } = &evidence.privileged_git_events {
                gaps.extend(g.clone());
            }
            if let EvidenceState::Missing { gaps: g } = &evidence.agent_action_log {
                gaps.extend(g.clone());
            }
            return vec![ControlFinding::indeterminate(
                id,
                "Privileged operation evidence is missing",
                vec![],
                gaps,
            )];
        }

        // --- Produce finding ---
        if subjects.is_empty() {
            let mut rationale = "No privileged operations detected".to_string();
            if git_gaps || action_gaps {
                rationale
                    .push_str(" (partial evidence — some operations may not have been captured)");
            }
            vec![ControlFinding::satisfied(id, rationale, vec![])]
        } else {
            let count = subjects.len();
            vec![ControlFinding::violated(
                id,
                format!("{count} privileged operation(s) detected"),
                subjects,
            )]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::control::ControlStatus;
    use crate::evidence::*;

    fn git_event(
        actor: &str,
        action: PrivilegedAction,
        branch: Option<&str>,
        tag: Option<&str>,
    ) -> PrivilegedGitEvent {
        PrivilegedGitEvent {
            actor: actor.to_string(),
            action,
            branch: branch.map(String::from),
            tag: tag.map(String::from),
            timestamp: None,
            commit_sha: None,
            detail: Some("test event".to_string()),
        }
    }

    fn action(command: &str) -> AgentAction {
        AgentAction {
            tool: "shell".to_string(),
            command: command.to_string(),
            timestamp: None,
        }
    }

    fn log_with(actions: Vec<AgentAction>) -> AgentActionLog {
        AgentActionLog {
            agent_id: "test-agent".to_string(),
            session_id: "session-1".to_string(),
            actions,
        }
    }

    // --- Git events ---

    #[test]
    fn no_events_no_actions_satisfied() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::complete(vec![]),
            agent_action_log: EvidenceState::complete(log_with(vec![])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Satisfied);
    }

    #[test]
    fn force_push_from_git_events() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::complete(vec![git_event(
                "bot",
                PrivilegedAction::ForcePush,
                Some("main"),
                None,
            )]),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
        assert!(findings[0].subjects[0].contains("force-push"));
    }

    #[test]
    fn admin_bypass_from_git_events() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::complete(vec![git_event(
                "admin",
                PrivilegedAction::AdminBypassProtection,
                Some("main"),
                None,
            )]),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
    }

    #[test]
    fn tag_deletion_from_git_events() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::complete(vec![git_event(
                "bot",
                PrivilegedAction::TagDeletion,
                None,
                Some("v1.0.0"),
            )]),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
        assert!(findings[0].subjects[0].contains("v1.0.0"));
    }

    // --- Action log command patterns ---

    #[test]
    fn rm_rf_from_action_log() {
        let b = EvidenceBundle {
            agent_action_log: EvidenceState::complete(log_with(vec![action("rm -rf /tmp")])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
        assert!(findings[0].subjects[0].contains("rm -rf /tmp"));
    }

    #[test]
    fn terraform_destroy_from_action_log() {
        let b = EvidenceBundle {
            agent_action_log: EvidenceState::complete(log_with(vec![action(
                "terraform destroy -auto-approve",
            )])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
    }

    #[test]
    fn safe_commands_satisfied() {
        let b = EvidenceBundle {
            agent_action_log: EvidenceState::complete(log_with(vec![
                action("cargo build"),
                action("git commit -m 'fix'"),
            ])),
            privileged_git_events: EvidenceState::complete(vec![]),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Satisfied);
    }

    #[test]
    fn custom_patterns_from_spec() {
        let b = EvidenceBundle {
            agent_action_log: EvidenceState::complete(log_with(vec![action(
                "vault delete secret/prod",
            )])),
            agent_spec: EvidenceState::complete(AgentSpec {
                custom_destructive_patterns: vec!["vault delete".to_string()],
                ..Default::default()
            }),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
    }

    // --- Combined sources ---

    #[test]
    fn git_events_and_action_log_combined() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::complete(vec![git_event(
                "bot",
                PrivilegedAction::ForcePush,
                Some("main"),
                None,
            )]),
            agent_action_log: EvidenceState::complete(log_with(vec![action("DROP TABLE users")])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
        assert_eq!(findings[0].subjects.len(), 2);
    }

    // --- Missing/NotApplicable ---

    #[test]
    fn both_missing_indeterminate() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::missing(vec![EvidenceGap::CollectionFailed {
                source: "webhook".into(),
                subject: "events".into(),
                detail: "down".into(),
            }]),
            agent_action_log: EvidenceState::missing(vec![EvidenceGap::CollectionFailed {
                source: "monitor".into(),
                subject: "log".into(),
                detail: "down".into(),
            }]),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Indeterminate);
        assert_eq!(findings[0].evidence_gaps.len(), 2);
    }

    #[test]
    fn both_not_applicable() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::not_applicable(),
            agent_action_log: EvidenceState::not_applicable(),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::NotApplicable);
    }

    #[test]
    fn one_missing_one_present_still_evaluates() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::missing(vec![]),
            agent_action_log: EvidenceState::complete(log_with(vec![action("rm -rf /")])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
    }

    #[test]
    fn case_insensitive_matching() {
        let b = EvidenceBundle {
            agent_action_log: EvidenceState::complete(log_with(vec![action("DROP TABLE users")])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Violated);
    }

    #[test]
    fn partial_evidence_notes_gaps() {
        let b = EvidenceBundle {
            privileged_git_events: EvidenceState::partial(
                vec![],
                vec![EvidenceGap::Truncated {
                    source: "webhook".into(),
                    subject: "events".into(),
                }],
            ),
            agent_action_log: EvidenceState::complete(log_with(vec![])),
            ..Default::default()
        };
        let findings = PrivilegedOperationAuditControl.evaluate(&b);
        assert_eq!(findings[0].status, ControlStatus::Satisfied);
        assert!(findings[0].rationale.contains("partial evidence"));
    }
}