Skip to main content

libverify_core/
control.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5use crate::evidence::{EvidenceBundle, EvidenceGap, EvidenceState, RepositoryPosture};
6
7/// A string-based control identifier, enabling open extensibility.
8///
9/// Built-in controls use kebab-case IDs (e.g. "review-independence").
10/// Platform-specific verifiers can register controls with their own IDs
11/// (e.g. "jira-linkage", "bitbucket-pipeline-status").
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(transparent)]
14pub struct ControlId(String);
15
16impl ControlId {
17    pub fn new(id: impl Into<String>) -> Self {
18        Self(id.into())
19    }
20
21    pub fn as_str(&self) -> &str {
22        &self.0
23    }
24}
25
26impl fmt::Display for ControlId {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.write_str(&self.0)
29    }
30}
31
32impl AsRef<str> for ControlId {
33    fn as_ref(&self) -> &str {
34        &self.0
35    }
36}
37
38impl std::borrow::Borrow<str> for ControlId {
39    fn borrow(&self) -> &str {
40        &self.0
41    }
42}
43
44impl From<&str> for ControlId {
45    fn from(s: &str) -> Self {
46        Self(s.to_string())
47    }
48}
49
50impl From<String> for ControlId {
51    fn from(s: String) -> Self {
52        Self(s)
53    }
54}
55
56// --- Built-in control IDs (constants for compile-time safety) ---
57
58pub mod builtin {
59    use super::ControlId;
60
61    // Source Track
62    pub const SOURCE_AUTHENTICITY: &str = "source-authenticity";
63    pub const REVIEW_INDEPENDENCE: &str = "review-independence";
64    pub const BRANCH_HISTORY_INTEGRITY: &str = "branch-history-integrity";
65    pub const BRANCH_PROTECTION_ENFORCEMENT: &str = "branch-protection-enforcement";
66    pub const TWO_PARTY_REVIEW: &str = "two-party-review";
67
68    // Build Track
69    pub const BUILD_PROVENANCE: &str = "build-provenance";
70    pub const REQUIRED_STATUS_CHECKS: &str = "required-status-checks";
71    pub const HOSTED_BUILD_PLATFORM: &str = "hosted-build-platform";
72    pub const PROVENANCE_AUTHENTICITY: &str = "provenance-authenticity";
73    pub const BUILD_ISOLATION: &str = "build-isolation";
74
75    // Dependencies Track
76    pub const DEPENDENCY_SIGNATURE: &str = "dependency-signature";
77    pub const DEPENDENCY_PROVENANCE_CHECK: &str = "dependency-provenance";
78    pub const DEPENDENCY_SIGNER_VERIFIED: &str = "dependency-signer-verified";
79    pub const DEPENDENCY_COMPLETENESS: &str = "dependency-completeness";
80
81    // Compliance (platform-neutral naming)
82    pub const CHANGE_REQUEST_SIZE: &str = "change-request-size";
83    pub const TEST_COVERAGE: &str = "test-coverage";
84    pub const SCOPED_CHANGE: &str = "scoped-change";
85    pub const ISSUE_LINKAGE: &str = "issue-linkage";
86    pub const STALE_REVIEW: &str = "stale-review";
87    pub const DESCRIPTION_QUALITY: &str = "description-quality";
88    pub const MERGE_COMMIT_POLICY: &str = "merge-commit-policy";
89    pub const CONVENTIONAL_TITLE: &str = "conventional-title";
90    pub const SECURITY_FILE_CHANGE: &str = "security-file-change";
91    pub const RELEASE_TRACEABILITY: &str = "release-traceability";
92
93    // ASPM / Repository Posture
94    pub const CODEOWNERS_COVERAGE: &str = "codeowners-coverage";
95    pub const SECRET_SCANNING: &str = "secret-scanning";
96    pub const VULNERABILITY_SCANNING: &str = "vulnerability-scanning";
97    pub const SECURITY_POLICY: &str = "security-policy";
98
99    // Enterprise Posture
100    pub const CODE_SCANNING_ALERTS_RESOLVED: &str = "code-scanning-alerts-resolved";
101    pub const RELEASE_ASSET_ATTESTATION: &str = "release-asset-attestation";
102    pub const PRIVILEGED_WORKFLOW_DETECTION: &str = "privileged-workflow-detection";
103    pub const SECURITY_TEST_IN_CI: &str = "security-test-in-ci";
104
105    // Supply Chain Transparency
106    pub const LICENSE_COMPLIANCE: &str = "license-compliance";
107    pub const SBOM_COMPLETENESS: &str = "sbom-completeness";
108
109    // Layer 2: Deterministic Gates
110    pub const HARNESS_GATE: &str = "harness-gate";
111    pub const COVERAGE_THRESHOLD: &str = "coverage-threshold";
112
113    // Container Image Attestation
114    pub const CONTAINER_SIGNATURE: &str = "container-signature";
115    pub const CONTAINER_PROVENANCE: &str = "container-provenance";
116
117    // AI-ops (agent execution verification)
118    pub const AGENT_SPEC_CONFORMANCE: &str = "agent-spec-conformance";
119    pub const PRIVILEGED_OPERATION_AUDIT: &str = "privileged-operation-audit";
120    pub const MCP_SCOPE_CHECK: &str = "mcp-scope-check";
121    pub const NETWORK_EGRESS_AUDIT: &str = "network-egress-audit";
122
123    /// All 42 built-in control IDs.
124    pub const ALL: &[&str] = &[
125        SOURCE_AUTHENTICITY,
126        REVIEW_INDEPENDENCE,
127        BRANCH_HISTORY_INTEGRITY,
128        BRANCH_PROTECTION_ENFORCEMENT,
129        TWO_PARTY_REVIEW,
130        BUILD_PROVENANCE,
131        REQUIRED_STATUS_CHECKS,
132        HOSTED_BUILD_PLATFORM,
133        PROVENANCE_AUTHENTICITY,
134        BUILD_ISOLATION,
135        DEPENDENCY_SIGNATURE,
136        DEPENDENCY_PROVENANCE_CHECK,
137        DEPENDENCY_SIGNER_VERIFIED,
138        DEPENDENCY_COMPLETENESS,
139        CHANGE_REQUEST_SIZE,
140        TEST_COVERAGE,
141        SCOPED_CHANGE,
142        ISSUE_LINKAGE,
143        STALE_REVIEW,
144        DESCRIPTION_QUALITY,
145        MERGE_COMMIT_POLICY,
146        CONVENTIONAL_TITLE,
147        SECURITY_FILE_CHANGE,
148        RELEASE_TRACEABILITY,
149        CODEOWNERS_COVERAGE,
150        SECRET_SCANNING,
151        VULNERABILITY_SCANNING,
152        SECURITY_POLICY,
153        CODE_SCANNING_ALERTS_RESOLVED,
154        RELEASE_ASSET_ATTESTATION,
155        PRIVILEGED_WORKFLOW_DETECTION,
156        SECURITY_TEST_IN_CI,
157        LICENSE_COMPLIANCE,
158        SBOM_COMPLETENESS,
159        HARNESS_GATE,
160        COVERAGE_THRESHOLD,
161        CONTAINER_SIGNATURE,
162        CONTAINER_PROVENANCE,
163        AGENT_SPEC_CONFORMANCE,
164        PRIVILEGED_OPERATION_AUDIT,
165        MCP_SCOPE_CHECK,
166        NETWORK_EGRESS_AUDIT,
167    ];
168
169    /// Returns a ControlId for a built-in constant.
170    pub fn id(s: &str) -> ControlId {
171        ControlId::new(s)
172    }
173}
174
175/// Outcome of evaluating a single control against evidence.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "snake_case")]
178pub enum ControlStatus {
179    Satisfied,
180    Violated,
181    Indeterminate,
182    NotApplicable,
183}
184
185impl ControlStatus {
186    pub fn as_str(&self) -> &'static str {
187        match self {
188            Self::Satisfied => "satisfied",
189            Self::Violated => "violated",
190            Self::Indeterminate => "indeterminate",
191            Self::NotApplicable => "not_applicable",
192        }
193    }
194}
195
196impl fmt::Display for ControlStatus {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        f.write_str(self.as_str())
199    }
200}
201
202/// Result of a single control evaluation.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct ControlFinding {
205    pub control_id: ControlId,
206    pub status: ControlStatus,
207    pub rationale: String,
208    pub subjects: Vec<String>,
209    pub evidence_gaps: Vec<EvidenceGap>,
210}
211
212impl ControlFinding {
213    pub fn satisfied(
214        control_id: ControlId,
215        rationale: impl Into<String>,
216        subjects: Vec<String>,
217    ) -> Self {
218        Self {
219            control_id,
220            status: ControlStatus::Satisfied,
221            rationale: rationale.into(),
222            subjects,
223            evidence_gaps: Vec::new(),
224        }
225    }
226
227    pub fn violated(
228        control_id: ControlId,
229        rationale: impl Into<String>,
230        subjects: Vec<String>,
231    ) -> Self {
232        Self {
233            control_id,
234            status: ControlStatus::Violated,
235            rationale: rationale.into(),
236            subjects,
237            evidence_gaps: Vec::new(),
238        }
239    }
240
241    pub fn indeterminate(
242        control_id: ControlId,
243        rationale: impl Into<String>,
244        subjects: Vec<String>,
245        evidence_gaps: Vec<EvidenceGap>,
246    ) -> Self {
247        Self {
248            control_id,
249            status: ControlStatus::Indeterminate,
250            rationale: rationale.into(),
251            subjects,
252            evidence_gaps,
253        }
254    }
255
256    pub fn not_applicable(control_id: ControlId, rationale: impl Into<String>) -> Self {
257        Self {
258            control_id,
259            status: ControlStatus::NotApplicable,
260            rationale: rationale.into(),
261            subjects: Vec::new(),
262            evidence_gaps: Vec::new(),
263        }
264    }
265
266    /// Extracts `RepositoryPosture` from evidence, returning appropriate
267    /// `Indeterminate` or `NotApplicable` findings for non-complete states.
268    ///
269    /// Use in posture controls to eliminate repeated `match` boilerplate:
270    /// ```ignore
271    /// let posture = match ControlFinding::extract_posture(self.id(), evidence) {
272    ///     Ok(p) => p,
273    ///     Err(findings) => return findings,
274    /// };
275    /// ```
276    pub fn extract_posture(
277        id: ControlId,
278        evidence: &EvidenceBundle,
279    ) -> Result<&RepositoryPosture, Vec<ControlFinding>> {
280        match &evidence.repository_posture {
281            EvidenceState::Complete { value } | EvidenceState::Partial { value, .. } => Ok(value),
282            EvidenceState::Missing { gaps } => Err(vec![ControlFinding::indeterminate(
283                id,
284                "Repository posture evidence could not be collected",
285                vec![],
286                gaps.clone(),
287            )]),
288            EvidenceState::NotApplicable => Err(vec![ControlFinding::not_applicable(
289                id,
290                "Repository posture not applicable",
291            )]),
292        }
293    }
294}
295
296/// A verifiable SDLC control that produces findings from evidence.
297pub trait Control: Send + Sync {
298    /// Returns the unique identifier for this control.
299    fn id(&self) -> ControlId;
300
301    /// Human-readable description for SARIF rule output.
302    fn description(&self) -> &'static str {
303        "Custom control"
304    }
305
306    /// SOC2 Trust Services Criteria this control maps to (e.g., &["CC6.1", "CC8.1"]).
307    /// Returns empty slice for controls not mapped to SOC2.
308    fn tsc_criteria(&self) -> &'static [&'static str] {
309        builtin_tsc_mapping(self.id().as_str())
310    }
311
312    /// Actionable remediation hint shown when the control fails or needs review.
313    fn remediation_hint(&self) -> Option<&'static str> {
314        builtin_remediation_hint(self.id().as_str())
315    }
316
317    /// Evaluates the evidence bundle and returns one finding per subject.
318    fn evaluate(&self, evidence: &EvidenceBundle) -> Vec<ControlFinding>;
319}
320
321/// Returns an actionable remediation hint for a built-in control ID.
322pub fn builtin_remediation_hint(id: &str) -> Option<&'static str> {
323    match id {
324        builtin::SOURCE_AUTHENTICITY => Some("Sign commits: git config commit.gpgsign true"),
325        builtin::REVIEW_INDEPENDENCE => {
326            Some("Ensure PRs are reviewed by someone other than the author")
327        }
328        builtin::BRANCH_HISTORY_INTEGRITY => {
329            Some("Use linear history (rebase/squash, avoid merge commits)")
330        }
331        builtin::BRANCH_PROTECTION_ENFORCEMENT => {
332            Some("Enable branch protection rules at Settings > Branches")
333        }
334        builtin::TWO_PARTY_REVIEW => {
335            Some("Require at least 2 reviewers in branch protection rules")
336        }
337        builtin::REQUIRED_STATUS_CHECKS => {
338            Some("Add required status checks in branch protection rules")
339        }
340        builtin::BUILD_PROVENANCE => {
341            Some("Generate SLSA provenance with slsa-framework/slsa-github-generator")
342        }
343        builtin::HOSTED_BUILD_PLATFORM => Some("Use GitHub-hosted runners instead of self-hosted"),
344        builtin::PROVENANCE_AUTHENTICITY => {
345            Some("Verify build provenance signatures with cosign/slsa-verifier")
346        }
347        builtin::BUILD_ISOLATION => Some("Ensure builds run in ephemeral, isolated environments"),
348        builtin::DEPENDENCY_SIGNATURE => {
349            Some("Use signed dependencies; verify with cosign or sigstore")
350        }
351        builtin::DEPENDENCY_PROVENANCE_CHECK => {
352            Some("Ensure dependencies publish SLSA provenance attestations")
353        }
354        builtin::DEPENDENCY_SIGNER_VERIFIED => {
355            Some("Verify dependency signers against a trusted list")
356        }
357        builtin::DEPENDENCY_COMPLETENESS => {
358            Some("Ensure all transitive dependencies have provenance")
359        }
360        builtin::CHANGE_REQUEST_SIZE => Some(
361            "Keep PRs small and focused; split large changes. Monorepo cross-package PRs may false-positive here -- use --exclude change-request-size",
362        ),
363        builtin::TEST_COVERAGE => Some(
364            "Add or update tests for changed source files. Dependency-only PRs may false-positive here -- use --exclude test-coverage",
365        ),
366        builtin::SCOPED_CHANGE => Some(
367            "Limit PR to a single logical change; split unrelated changes. In monorepos, features spanning multiple packages are expected -- use --exclude scoped-change",
368        ),
369        builtin::ISSUE_LINKAGE => Some(
370            "Reference an issue in the PR body: Fixes #123 or Closes #456. Bot PRs (Dependabot/Renovate) don't link issues -- use --exclude issue-linkage",
371        ),
372        builtin::DESCRIPTION_QUALITY => {
373            Some("Add a meaningful PR description explaining the change")
374        }
375        builtin::MERGE_COMMIT_POLICY => {
376            Some("Use squash or rebase merge strategy instead of merge commits")
377        }
378        builtin::CONVENTIONAL_TITLE => Some(
379            "Use Conventional Commits format: type(scope): description. Bot PRs use their own title format -- use --exclude conventional-title",
380        ),
381        builtin::STALE_REVIEW => Some("Re-request review if changes were pushed after approval"),
382        builtin::SECURITY_FILE_CHANGE => {
383            Some("Security-sensitive file changes require additional review")
384        }
385        builtin::RELEASE_TRACEABILITY => Some("Link release to merged PRs and resolved issues"),
386        builtin::CODEOWNERS_COVERAGE => Some("Add a CODEOWNERS file to define code ownership"),
387        builtin::SECRET_SCANNING => {
388            Some("Enable secret scanning at Settings > Code security and analysis")
389        }
390        builtin::VULNERABILITY_SCANNING => {
391            Some("Enable Dependabot alerts at Settings > Code security and analysis")
392        }
393        builtin::SECURITY_POLICY => {
394            Some("Add a SECURITY.md file with vulnerability reporting instructions")
395        }
396        builtin::CODE_SCANNING_ALERTS_RESOLVED => {
397            Some("Resolve open code scanning alerts at Security > Code scanning alerts")
398        }
399        builtin::RELEASE_ASSET_ATTESTATION => {
400            Some("Attest release assets with gh attestation or sigstore/cosign")
401        }
402        builtin::PRIVILEGED_WORKFLOW_DETECTION => {
403            Some("Avoid pull_request_target with checkout of PR code in workflows")
404        }
405        builtin::SECURITY_TEST_IN_CI => {
406            Some("Add CodeQL or Semgrep to GitHub Actions: github/codeql-action/analyze")
407        }
408        builtin::LICENSE_COMPLIANCE => Some(
409            "Review copyleft dependencies (GPL, AGPL, SSPL) and replace with permissively-licensed alternatives or obtain legal approval",
410        ),
411        builtin::SBOM_COMPLETENESS => {
412            Some("Generate SBOM with syft, cyclonedx-cli, or cargo-sbom and attach to releases")
413        }
414        builtin::HARNESS_GATE => {
415            Some("Fix failing CI checks before merging. Run tests locally: cargo test / npm test")
416        }
417        builtin::COVERAGE_THRESHOLD => {
418            Some("Increase test coverage. Current coverage is below the minimum threshold")
419        }
420        builtin::CONTAINER_SIGNATURE => {
421            Some("Sign container images with cosign: cosign sign --yes ghcr.io/owner/repo:tag")
422        }
423        builtin::CONTAINER_PROVENANCE => Some(
424            "Generate SLSA provenance for container images using slsa-framework/slsa-github-generator or ko build --provenance",
425        ),
426        builtin::AGENT_SPEC_CONFORMANCE => Some(
427            "Define allowed_paths, forbidden_paths, and budget in agent spec to constrain agent scope",
428        ),
429        builtin::PRIVILEGED_OPERATION_AUDIT => Some(
430            "Review privileged git operations (force push, admin bypass, tag deletion) and restrict agent permissions",
431        ),
432        builtin::MCP_SCOPE_CHECK => Some(
433            "Restrict MCP tool access in agent spec. Add allowed_tools entries like 'mcp:github/*' or remove forbidden servers",
434        ),
435        builtin::NETWORK_EGRESS_AUDIT => Some(
436            "Review agent network access. Restrict outbound connections in agent spec or network policy",
437        ),
438        _ => None,
439    }
440}
441
442/// Returns SOC2 Trust Services Criteria for a built-in control ID.
443pub fn builtin_tsc_mapping(id: &str) -> &'static [&'static str] {
444    match id {
445        // CC6: Logical and Physical Access Controls
446        builtin::SOURCE_AUTHENTICITY => &["CC6.1"],
447        builtin::BRANCH_PROTECTION_ENFORCEMENT => &["CC6.1", "CC8.1"],
448        builtin::CODEOWNERS_COVERAGE => &["CC6.1"],
449        builtin::SECRET_SCANNING => &["CC6.1", "CC6.6"],
450        // CC7: System Operations
451        builtin::ISSUE_LINKAGE => &["CC7.2"],
452        builtin::STALE_REVIEW => &["CC7.2"],
453        builtin::SECURITY_FILE_CHANGE => &["CC7.2"],
454        builtin::RELEASE_TRACEABILITY => &["CC7.2"],
455        builtin::REQUIRED_STATUS_CHECKS => &["CC7.1"],
456        builtin::VULNERABILITY_SCANNING => &["CC7.1"],
457        builtin::SECURITY_POLICY => &["CC7.3", "CC7.4"],
458        // CC8: Change Management
459        builtin::REVIEW_INDEPENDENCE => &["CC8.1"],
460        builtin::TWO_PARTY_REVIEW => &["CC8.1"],
461        builtin::CHANGE_REQUEST_SIZE => &["CC8.1"],
462        builtin::TEST_COVERAGE => &["CC8.1"],
463        builtin::SCOPED_CHANGE => &["CC8.1"],
464        builtin::DESCRIPTION_QUALITY => &["CC8.1"],
465        builtin::MERGE_COMMIT_POLICY => &["CC8.1"],
466        builtin::CONVENTIONAL_TITLE => &["CC8.1"],
467        builtin::BRANCH_HISTORY_INTEGRITY => &["CC8.1"],
468        // PI: Processing Integrity
469        builtin::BUILD_PROVENANCE => &["PI1.4"],
470        builtin::HOSTED_BUILD_PLATFORM => &["PI1.4"],
471        builtin::PROVENANCE_AUTHENTICITY => &["PI1.4"],
472        builtin::BUILD_ISOLATION => &["PI1.4"],
473        // Dependencies (CC7.1 + PI)
474        builtin::DEPENDENCY_SIGNATURE => &["CC7.1", "PI1.4"],
475        builtin::DEPENDENCY_PROVENANCE_CHECK => &["CC7.1", "PI1.4"],
476        builtin::DEPENDENCY_SIGNER_VERIFIED => &["CC7.1", "PI1.4"],
477        builtin::DEPENDENCY_COMPLETENESS => &["CC7.1", "PI1.4"],
478        // Enterprise Posture
479        builtin::CODE_SCANNING_ALERTS_RESOLVED => &["CC7.1"],
480        builtin::RELEASE_ASSET_ATTESTATION => &["PI1.4"],
481        builtin::PRIVILEGED_WORKFLOW_DETECTION => &["CC6.1", "CC8.1"],
482        // Supply Chain Transparency
483        builtin::LICENSE_COMPLIANCE => &["CC7.1"],
484        builtin::SBOM_COMPLETENESS => &["CC7.1", "PI1.4"],
485        // Layer 2: Deterministic Gates
486        builtin::HARNESS_GATE => &["CC7.1", "CC8.1"],
487        builtin::COVERAGE_THRESHOLD => &["CC8.1"],
488        // Container Image Attestation
489        builtin::CONTAINER_SIGNATURE => &["PI1.4"],
490        builtin::CONTAINER_PROVENANCE => &["PI1.4"],
491        // AI-ops (agent execution verification)
492        builtin::AGENT_SPEC_CONFORMANCE => &["CC6.1", "CC8.1"],
493        builtin::PRIVILEGED_OPERATION_AUDIT => &["CC6.1", "CC7.2", "CC8.1"],
494        builtin::MCP_SCOPE_CHECK => &["CC6.1", "CC8.1"],
495        builtin::NETWORK_EGRESS_AUDIT => &["CC6.1", "CC6.6"],
496        _ => &[],
497    }
498}
499
500/// Runs every control against the evidence bundle and collects all findings.
501pub fn evaluate_all(
502    controls: &[Box<dyn Control>],
503    evidence: &EvidenceBundle,
504) -> Vec<ControlFinding> {
505    let mut findings = Vec::new();
506    for control in controls {
507        findings.extend(control.evaluate(evidence));
508    }
509    findings
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515
516    #[test]
517    fn control_id_display() {
518        let id = ControlId::new("review-independence");
519        assert_eq!(id.to_string(), "review-independence");
520        assert_eq!(id.as_str(), "review-independence");
521    }
522
523    #[test]
524    fn control_id_from_str() {
525        let id: ControlId = "source-authenticity".into();
526        assert_eq!(id.as_str(), "source-authenticity");
527    }
528
529    #[test]
530    fn all_builtins_have_remediation_hints() {
531        for id in builtin::ALL {
532            assert!(
533                builtin_remediation_hint(id).is_some(),
534                "missing remediation hint for built-in control: {id}"
535            );
536        }
537    }
538
539    #[test]
540    fn builtin_ids_are_unique() {
541        let mut seen = std::collections::HashSet::new();
542        for id in builtin::ALL {
543            assert!(seen.insert(id), "duplicate built-in ID: {id}");
544        }
545    }
546}