libverify-core 0.12.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::evidence::{EvidenceBundle, EvidenceGap, EvidenceState, RepositoryPosture};

/// A string-based control identifier, enabling open extensibility.
///
/// Built-in controls use kebab-case IDs (e.g. "review-independence").
/// Platform-specific verifiers can register controls with their own IDs
/// (e.g. "jira-linkage", "bitbucket-pipeline-status").
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ControlId(String);

impl ControlId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ControlId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for ControlId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::borrow::Borrow<str> for ControlId {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl From<&str> for ControlId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl From<String> for ControlId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

// --- Built-in control IDs (constants for compile-time safety) ---

pub mod builtin {
    use super::ControlId;

    // Source Track
    pub const SOURCE_AUTHENTICITY: &str = "source-authenticity";
    pub const REVIEW_INDEPENDENCE: &str = "review-independence";
    pub const BRANCH_HISTORY_INTEGRITY: &str = "branch-history-integrity";
    pub const BRANCH_PROTECTION_ENFORCEMENT: &str = "branch-protection-enforcement";
    pub const TWO_PARTY_REVIEW: &str = "two-party-review";

    // Build Track
    pub const BUILD_PROVENANCE: &str = "build-provenance";
    pub const REQUIRED_STATUS_CHECKS: &str = "required-status-checks";
    pub const HOSTED_BUILD_PLATFORM: &str = "hosted-build-platform";
    pub const PROVENANCE_AUTHENTICITY: &str = "provenance-authenticity";
    pub const BUILD_ISOLATION: &str = "build-isolation";

    // Dependencies Track
    pub const DEPENDENCY_SIGNATURE: &str = "dependency-signature";
    pub const DEPENDENCY_PROVENANCE_CHECK: &str = "dependency-provenance";
    pub const DEPENDENCY_SIGNER_VERIFIED: &str = "dependency-signer-verified";
    pub const DEPENDENCY_COMPLETENESS: &str = "dependency-completeness";

    // Compliance (platform-neutral naming)
    pub const CHANGE_REQUEST_SIZE: &str = "change-request-size";
    pub const TEST_COVERAGE: &str = "test-coverage";
    pub const SCOPED_CHANGE: &str = "scoped-change";
    pub const ISSUE_LINKAGE: &str = "issue-linkage";
    pub const STALE_REVIEW: &str = "stale-review";
    pub const DESCRIPTION_QUALITY: &str = "description-quality";
    pub const MERGE_COMMIT_POLICY: &str = "merge-commit-policy";
    pub const CONVENTIONAL_TITLE: &str = "conventional-title";
    pub const SECURITY_FILE_CHANGE: &str = "security-file-change";
    pub const RELEASE_TRACEABILITY: &str = "release-traceability";

    // ASPM / Repository Posture
    pub const CODEOWNERS_COVERAGE: &str = "codeowners-coverage";
    pub const SECRET_SCANNING: &str = "secret-scanning";
    pub const VULNERABILITY_SCANNING: &str = "vulnerability-scanning";
    pub const SECURITY_POLICY: &str = "security-policy";

    // Enterprise Posture
    pub const CODE_SCANNING_ALERTS_RESOLVED: &str = "code-scanning-alerts-resolved";
    pub const RELEASE_ASSET_ATTESTATION: &str = "release-asset-attestation";
    pub const PRIVILEGED_WORKFLOW_DETECTION: &str = "privileged-workflow-detection";
    pub const SECURITY_TEST_IN_CI: &str = "security-test-in-ci";

    // AI-ops (agent execution verification)
    pub const AGENT_SPEC_CONFORMANCE: &str = "agent-spec-conformance";
    pub const PRIVILEGED_OPERATION_AUDIT: &str = "privileged-operation-audit";

    /// All 34 built-in control IDs.
    pub const ALL: &[&str] = &[
        SOURCE_AUTHENTICITY,
        REVIEW_INDEPENDENCE,
        BRANCH_HISTORY_INTEGRITY,
        BRANCH_PROTECTION_ENFORCEMENT,
        TWO_PARTY_REVIEW,
        BUILD_PROVENANCE,
        REQUIRED_STATUS_CHECKS,
        HOSTED_BUILD_PLATFORM,
        PROVENANCE_AUTHENTICITY,
        BUILD_ISOLATION,
        DEPENDENCY_SIGNATURE,
        DEPENDENCY_PROVENANCE_CHECK,
        DEPENDENCY_SIGNER_VERIFIED,
        DEPENDENCY_COMPLETENESS,
        CHANGE_REQUEST_SIZE,
        TEST_COVERAGE,
        SCOPED_CHANGE,
        ISSUE_LINKAGE,
        STALE_REVIEW,
        DESCRIPTION_QUALITY,
        MERGE_COMMIT_POLICY,
        CONVENTIONAL_TITLE,
        SECURITY_FILE_CHANGE,
        RELEASE_TRACEABILITY,
        CODEOWNERS_COVERAGE,
        SECRET_SCANNING,
        VULNERABILITY_SCANNING,
        SECURITY_POLICY,
        CODE_SCANNING_ALERTS_RESOLVED,
        RELEASE_ASSET_ATTESTATION,
        PRIVILEGED_WORKFLOW_DETECTION,
        SECURITY_TEST_IN_CI,
        AGENT_SPEC_CONFORMANCE,
        PRIVILEGED_OPERATION_AUDIT,
    ];

    /// Returns a ControlId for a built-in constant.
    pub fn id(s: &str) -> ControlId {
        ControlId::new(s)
    }
}

/// Outcome of evaluating a single control against evidence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ControlStatus {
    Satisfied,
    Violated,
    Indeterminate,
    NotApplicable,
}

impl ControlStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Satisfied => "satisfied",
            Self::Violated => "violated",
            Self::Indeterminate => "indeterminate",
            Self::NotApplicable => "not_applicable",
        }
    }
}

impl fmt::Display for ControlStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Result of a single control evaluation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ControlFinding {
    pub control_id: ControlId,
    pub status: ControlStatus,
    pub rationale: String,
    pub subjects: Vec<String>,
    pub evidence_gaps: Vec<EvidenceGap>,
}

impl ControlFinding {
    pub fn satisfied(
        control_id: ControlId,
        rationale: impl Into<String>,
        subjects: Vec<String>,
    ) -> Self {
        Self {
            control_id,
            status: ControlStatus::Satisfied,
            rationale: rationale.into(),
            subjects,
            evidence_gaps: Vec::new(),
        }
    }

    pub fn violated(
        control_id: ControlId,
        rationale: impl Into<String>,
        subjects: Vec<String>,
    ) -> Self {
        Self {
            control_id,
            status: ControlStatus::Violated,
            rationale: rationale.into(),
            subjects,
            evidence_gaps: Vec::new(),
        }
    }

    pub fn indeterminate(
        control_id: ControlId,
        rationale: impl Into<String>,
        subjects: Vec<String>,
        evidence_gaps: Vec<EvidenceGap>,
    ) -> Self {
        Self {
            control_id,
            status: ControlStatus::Indeterminate,
            rationale: rationale.into(),
            subjects,
            evidence_gaps,
        }
    }

    pub fn not_applicable(control_id: ControlId, rationale: impl Into<String>) -> Self {
        Self {
            control_id,
            status: ControlStatus::NotApplicable,
            rationale: rationale.into(),
            subjects: Vec::new(),
            evidence_gaps: Vec::new(),
        }
    }

    /// Extracts `RepositoryPosture` from evidence, returning appropriate
    /// `Indeterminate` or `NotApplicable` findings for non-complete states.
    ///
    /// Use in posture controls to eliminate repeated `match` boilerplate:
    /// ```ignore
    /// let posture = match ControlFinding::extract_posture(self.id(), evidence) {
    ///     Ok(p) => p,
    ///     Err(findings) => return findings,
    /// };
    /// ```
    pub fn extract_posture(
        id: ControlId,
        evidence: &EvidenceBundle,
    ) -> Result<&RepositoryPosture, Vec<ControlFinding>> {
        match &evidence.repository_posture {
            EvidenceState::Complete { value } | EvidenceState::Partial { value, .. } => Ok(value),
            EvidenceState::Missing { gaps } => Err(vec![ControlFinding::indeterminate(
                id,
                "Repository posture evidence could not be collected",
                vec![],
                gaps.clone(),
            )]),
            EvidenceState::NotApplicable => Err(vec![ControlFinding::not_applicable(
                id,
                "Repository posture not applicable",
            )]),
        }
    }
}

/// A verifiable SDLC control that produces findings from evidence.
pub trait Control: Send + Sync {
    /// Returns the unique identifier for this control.
    fn id(&self) -> ControlId;

    /// Human-readable description for SARIF rule output.
    fn description(&self) -> &'static str {
        "Custom control"
    }

    /// SOC2 Trust Services Criteria this control maps to (e.g., &["CC6.1", "CC8.1"]).
    /// Returns empty slice for controls not mapped to SOC2.
    fn tsc_criteria(&self) -> &'static [&'static str] {
        builtin_tsc_mapping(self.id().as_str())
    }

    /// Actionable remediation hint shown when the control fails or needs review.
    fn remediation_hint(&self) -> Option<&'static str> {
        builtin_remediation_hint(self.id().as_str())
    }

    /// Evaluates the evidence bundle and returns one finding per subject.
    fn evaluate(&self, evidence: &EvidenceBundle) -> Vec<ControlFinding>;
}

/// Returns an actionable remediation hint for a built-in control ID.
pub fn builtin_remediation_hint(id: &str) -> Option<&'static str> {
    match id {
        builtin::SOURCE_AUTHENTICITY => Some("Sign commits: git config commit.gpgsign true"),
        builtin::REVIEW_INDEPENDENCE => {
            Some("Ensure PRs are reviewed by someone other than the author")
        }
        builtin::BRANCH_HISTORY_INTEGRITY => {
            Some("Use linear history (rebase/squash, avoid merge commits)")
        }
        builtin::BRANCH_PROTECTION_ENFORCEMENT => {
            Some("Enable branch protection rules at Settings > Branches")
        }
        builtin::TWO_PARTY_REVIEW => {
            Some("Require at least 2 reviewers in branch protection rules")
        }
        builtin::REQUIRED_STATUS_CHECKS => {
            Some("Add required status checks in branch protection rules")
        }
        builtin::BUILD_PROVENANCE => {
            Some("Generate SLSA provenance with slsa-framework/slsa-github-generator")
        }
        builtin::HOSTED_BUILD_PLATFORM => Some("Use GitHub-hosted runners instead of self-hosted"),
        builtin::PROVENANCE_AUTHENTICITY => {
            Some("Verify build provenance signatures with cosign/slsa-verifier")
        }
        builtin::BUILD_ISOLATION => Some("Ensure builds run in ephemeral, isolated environments"),
        builtin::DEPENDENCY_SIGNATURE => {
            Some("Use signed dependencies; verify with cosign or sigstore")
        }
        builtin::DEPENDENCY_PROVENANCE_CHECK => {
            Some("Ensure dependencies publish SLSA provenance attestations")
        }
        builtin::DEPENDENCY_SIGNER_VERIFIED => {
            Some("Verify dependency signers against a trusted list")
        }
        builtin::DEPENDENCY_COMPLETENESS => {
            Some("Ensure all transitive dependencies have provenance")
        }
        builtin::CHANGE_REQUEST_SIZE => Some(
            "Keep PRs small and focused; split large changes. Monorepo cross-package PRs may false-positive here -- use --exclude change-request-size",
        ),
        builtin::TEST_COVERAGE => Some(
            "Add or update tests for changed source files. Dependency-only PRs may false-positive here -- use --exclude test-coverage",
        ),
        builtin::SCOPED_CHANGE => Some(
            "Limit PR to a single logical change; split unrelated changes. In monorepos, features spanning multiple packages are expected -- use --exclude scoped-change",
        ),
        builtin::ISSUE_LINKAGE => Some(
            "Reference an issue in the PR body: Fixes #123 or Closes #456. Bot PRs (Dependabot/Renovate) don't link issues -- use --exclude issue-linkage",
        ),
        builtin::DESCRIPTION_QUALITY => {
            Some("Add a meaningful PR description explaining the change")
        }
        builtin::MERGE_COMMIT_POLICY => {
            Some("Use squash or rebase merge strategy instead of merge commits")
        }
        builtin::CONVENTIONAL_TITLE => Some(
            "Use Conventional Commits format: type(scope): description. Bot PRs use their own title format -- use --exclude conventional-title",
        ),
        builtin::STALE_REVIEW => Some("Re-request review if changes were pushed after approval"),
        builtin::SECURITY_FILE_CHANGE => {
            Some("Security-sensitive file changes require additional review")
        }
        builtin::RELEASE_TRACEABILITY => Some("Link release to merged PRs and resolved issues"),
        builtin::CODEOWNERS_COVERAGE => Some("Add a CODEOWNERS file to define code ownership"),
        builtin::SECRET_SCANNING => {
            Some("Enable secret scanning at Settings > Code security and analysis")
        }
        builtin::VULNERABILITY_SCANNING => {
            Some("Enable Dependabot alerts at Settings > Code security and analysis")
        }
        builtin::SECURITY_POLICY => {
            Some("Add a SECURITY.md file with vulnerability reporting instructions")
        }
        builtin::CODE_SCANNING_ALERTS_RESOLVED => {
            Some("Resolve open code scanning alerts at Security > Code scanning alerts")
        }
        builtin::RELEASE_ASSET_ATTESTATION => {
            Some("Attest release assets with gh attestation or sigstore/cosign")
        }
        builtin::PRIVILEGED_WORKFLOW_DETECTION => {
            Some("Avoid pull_request_target with checkout of PR code in workflows")
        }
        builtin::SECURITY_TEST_IN_CI => {
            Some("Add CodeQL or Semgrep to GitHub Actions: github/codeql-action/analyze")
        }
        builtin::AGENT_SPEC_CONFORMANCE => Some(
            "Define allowed_paths, forbidden_paths, and budget in agent spec to constrain agent scope",
        ),
        builtin::PRIVILEGED_OPERATION_AUDIT => Some(
            "Review privileged git operations (force push, admin bypass, tag deletion) and restrict agent permissions",
        ),
        _ => None,
    }
}

/// Returns SOC2 Trust Services Criteria for a built-in control ID.
pub fn builtin_tsc_mapping(id: &str) -> &'static [&'static str] {
    match id {
        // CC6: Logical and Physical Access Controls
        builtin::SOURCE_AUTHENTICITY => &["CC6.1"],
        builtin::BRANCH_PROTECTION_ENFORCEMENT => &["CC6.1", "CC8.1"],
        builtin::CODEOWNERS_COVERAGE => &["CC6.1"],
        builtin::SECRET_SCANNING => &["CC6.1", "CC6.6"],
        // CC7: System Operations
        builtin::ISSUE_LINKAGE => &["CC7.2"],
        builtin::STALE_REVIEW => &["CC7.2"],
        builtin::SECURITY_FILE_CHANGE => &["CC7.2"],
        builtin::RELEASE_TRACEABILITY => &["CC7.2"],
        builtin::REQUIRED_STATUS_CHECKS => &["CC7.1"],
        builtin::VULNERABILITY_SCANNING => &["CC7.1"],
        builtin::SECURITY_POLICY => &["CC7.3", "CC7.4"],
        // CC8: Change Management
        builtin::REVIEW_INDEPENDENCE => &["CC8.1"],
        builtin::TWO_PARTY_REVIEW => &["CC8.1"],
        builtin::CHANGE_REQUEST_SIZE => &["CC8.1"],
        builtin::TEST_COVERAGE => &["CC8.1"],
        builtin::SCOPED_CHANGE => &["CC8.1"],
        builtin::DESCRIPTION_QUALITY => &["CC8.1"],
        builtin::MERGE_COMMIT_POLICY => &["CC8.1"],
        builtin::CONVENTIONAL_TITLE => &["CC8.1"],
        builtin::BRANCH_HISTORY_INTEGRITY => &["CC8.1"],
        // PI: Processing Integrity
        builtin::BUILD_PROVENANCE => &["PI1.4"],
        builtin::HOSTED_BUILD_PLATFORM => &["PI1.4"],
        builtin::PROVENANCE_AUTHENTICITY => &["PI1.4"],
        builtin::BUILD_ISOLATION => &["PI1.4"],
        // Dependencies (CC7.1 + PI)
        builtin::DEPENDENCY_SIGNATURE => &["CC7.1", "PI1.4"],
        builtin::DEPENDENCY_PROVENANCE_CHECK => &["CC7.1", "PI1.4"],
        builtin::DEPENDENCY_SIGNER_VERIFIED => &["CC7.1", "PI1.4"],
        builtin::DEPENDENCY_COMPLETENESS => &["CC7.1", "PI1.4"],
        // Enterprise Posture
        builtin::CODE_SCANNING_ALERTS_RESOLVED => &["CC7.1"],
        builtin::RELEASE_ASSET_ATTESTATION => &["PI1.4"],
        builtin::PRIVILEGED_WORKFLOW_DETECTION => &["CC6.1", "CC8.1"],
        // AI-ops (agent execution verification)
        builtin::AGENT_SPEC_CONFORMANCE => &["CC6.1", "CC8.1"],
        builtin::PRIVILEGED_OPERATION_AUDIT => &["CC6.1", "CC7.2", "CC8.1"],
        _ => &[],
    }
}

/// Runs every control against the evidence bundle and collects all findings.
pub fn evaluate_all(
    controls: &[Box<dyn Control>],
    evidence: &EvidenceBundle,
) -> Vec<ControlFinding> {
    let mut findings = Vec::new();
    for control in controls {
        findings.extend(control.evaluate(evidence));
    }
    findings
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn control_id_display() {
        let id = ControlId::new("review-independence");
        assert_eq!(id.to_string(), "review-independence");
        assert_eq!(id.as_str(), "review-independence");
    }

    #[test]
    fn control_id_from_str() {
        let id: ControlId = "source-authenticity".into();
        assert_eq!(id.as_str(), "source-authenticity");
    }

    #[test]
    fn all_builtins_have_remediation_hints() {
        for id in builtin::ALL {
            assert!(
                builtin_remediation_hint(id).is_some(),
                "missing remediation hint for built-in control: {id}"
            );
        }
    }

    #[test]
    fn builtin_ids_are_unique() {
        let mut seen = std::collections::HashSet::new();
        for id in builtin::ALL {
            assert!(seen.insert(id), "duplicate built-in ID: {id}");
        }
    }
}