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 From<&str> for ControlId {
33    fn from(s: &str) -> Self {
34        Self(s.to_string())
35    }
36}
37
38impl From<String> for ControlId {
39    fn from(s: String) -> Self {
40        Self(s)
41    }
42}
43
44// --- Built-in control IDs (constants for compile-time safety) ---
45
46pub mod builtin {
47    use super::ControlId;
48
49    // Source Track
50    pub const SOURCE_AUTHENTICITY: &str = "source-authenticity";
51    pub const REVIEW_INDEPENDENCE: &str = "review-independence";
52    pub const BRANCH_HISTORY_INTEGRITY: &str = "branch-history-integrity";
53    pub const BRANCH_PROTECTION_ENFORCEMENT: &str = "branch-protection-enforcement";
54    pub const TWO_PARTY_REVIEW: &str = "two-party-review";
55
56    // Build Track
57    pub const BUILD_PROVENANCE: &str = "build-provenance";
58    pub const REQUIRED_STATUS_CHECKS: &str = "required-status-checks";
59    pub const HOSTED_BUILD_PLATFORM: &str = "hosted-build-platform";
60    pub const PROVENANCE_AUTHENTICITY: &str = "provenance-authenticity";
61    pub const BUILD_ISOLATION: &str = "build-isolation";
62
63    // Dependencies Track
64    pub const DEPENDENCY_SIGNATURE: &str = "dependency-signature";
65    pub const DEPENDENCY_PROVENANCE_CHECK: &str = "dependency-provenance";
66    pub const DEPENDENCY_SIGNER_VERIFIED: &str = "dependency-signer-verified";
67    pub const DEPENDENCY_COMPLETENESS: &str = "dependency-completeness";
68
69    // Compliance (platform-neutral naming)
70    pub const CHANGE_REQUEST_SIZE: &str = "change-request-size";
71    pub const TEST_COVERAGE: &str = "test-coverage";
72    pub const SCOPED_CHANGE: &str = "scoped-change";
73    pub const ISSUE_LINKAGE: &str = "issue-linkage";
74    pub const STALE_REVIEW: &str = "stale-review";
75    pub const DESCRIPTION_QUALITY: &str = "description-quality";
76    pub const MERGE_COMMIT_POLICY: &str = "merge-commit-policy";
77    pub const CONVENTIONAL_TITLE: &str = "conventional-title";
78    pub const SECURITY_FILE_CHANGE: &str = "security-file-change";
79    pub const RELEASE_TRACEABILITY: &str = "release-traceability";
80
81    // ASPM / Repository Posture
82    pub const CODEOWNERS_COVERAGE: &str = "codeowners-coverage";
83    pub const SECRET_SCANNING: &str = "secret-scanning";
84    pub const VULNERABILITY_SCANNING: &str = "vulnerability-scanning";
85    pub const SECURITY_POLICY: &str = "security-policy";
86
87    // Enterprise Posture
88    pub const SECRET_SCANNING_PUSH_PROTECTION: &str = "secret-scanning-push-protection";
89    pub const BRANCH_PROTECTION_ADMIN_ENFORCEMENT: &str = "branch-protection-admin-enforcement";
90    pub const DISMISS_STALE_REVIEWS_ON_PUSH: &str = "dismiss-stale-reviews-on-push";
91    pub const ACTIONS_PINNED_DEPENDENCIES: &str = "actions-pinned-dependencies";
92    pub const ENVIRONMENT_PROTECTION_RULES: &str = "environment-protection-rules";
93    pub const CODE_SCANNING_ALERTS_RESOLVED: &str = "code-scanning-alerts-resolved";
94    pub const DEPENDENCY_LICENSE_COMPLIANCE: &str = "dependency-license-compliance";
95    pub const SBOM_ATTESTATION: &str = "sbom-attestation";
96    pub const RELEASE_ASSET_ATTESTATION: &str = "release-asset-attestation";
97    pub const PRIVILEGED_WORKFLOW_DETECTION: &str = "privileged-workflow-detection";
98    pub const WORKFLOW_PERMISSIONS_RESTRICTED: &str = "workflow-permissions-restricted";
99    pub const DEPENDENCY_UPDATE_TOOL: &str = "dependency-update-tool";
100    pub const REPOSITORY_PERMISSIONS_AUDIT: &str = "repository-permissions-audit";
101
102    /// All 41 built-in control IDs.
103    pub const ALL: &[&str] = &[
104        SOURCE_AUTHENTICITY,
105        REVIEW_INDEPENDENCE,
106        BRANCH_HISTORY_INTEGRITY,
107        BRANCH_PROTECTION_ENFORCEMENT,
108        TWO_PARTY_REVIEW,
109        BUILD_PROVENANCE,
110        REQUIRED_STATUS_CHECKS,
111        HOSTED_BUILD_PLATFORM,
112        PROVENANCE_AUTHENTICITY,
113        BUILD_ISOLATION,
114        DEPENDENCY_SIGNATURE,
115        DEPENDENCY_PROVENANCE_CHECK,
116        DEPENDENCY_SIGNER_VERIFIED,
117        DEPENDENCY_COMPLETENESS,
118        CHANGE_REQUEST_SIZE,
119        TEST_COVERAGE,
120        SCOPED_CHANGE,
121        ISSUE_LINKAGE,
122        STALE_REVIEW,
123        DESCRIPTION_QUALITY,
124        MERGE_COMMIT_POLICY,
125        CONVENTIONAL_TITLE,
126        SECURITY_FILE_CHANGE,
127        RELEASE_TRACEABILITY,
128        CODEOWNERS_COVERAGE,
129        SECRET_SCANNING,
130        VULNERABILITY_SCANNING,
131        SECURITY_POLICY,
132        SECRET_SCANNING_PUSH_PROTECTION,
133        BRANCH_PROTECTION_ADMIN_ENFORCEMENT,
134        DISMISS_STALE_REVIEWS_ON_PUSH,
135        ACTIONS_PINNED_DEPENDENCIES,
136        ENVIRONMENT_PROTECTION_RULES,
137        CODE_SCANNING_ALERTS_RESOLVED,
138        DEPENDENCY_LICENSE_COMPLIANCE,
139        SBOM_ATTESTATION,
140        RELEASE_ASSET_ATTESTATION,
141        PRIVILEGED_WORKFLOW_DETECTION,
142        WORKFLOW_PERMISSIONS_RESTRICTED,
143        DEPENDENCY_UPDATE_TOOL,
144        REPOSITORY_PERMISSIONS_AUDIT,
145    ];
146
147    /// Returns a ControlId for a built-in constant.
148    pub fn id(s: &str) -> ControlId {
149        ControlId::new(s)
150    }
151}
152
153/// Outcome of evaluating a single control against evidence.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case")]
156pub enum ControlStatus {
157    Satisfied,
158    Violated,
159    Indeterminate,
160    NotApplicable,
161}
162
163impl ControlStatus {
164    pub fn as_str(&self) -> &'static str {
165        match self {
166            Self::Satisfied => "satisfied",
167            Self::Violated => "violated",
168            Self::Indeterminate => "indeterminate",
169            Self::NotApplicable => "not_applicable",
170        }
171    }
172}
173
174impl fmt::Display for ControlStatus {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        f.write_str(self.as_str())
177    }
178}
179
180/// Result of a single control evaluation.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182pub struct ControlFinding {
183    pub control_id: ControlId,
184    pub status: ControlStatus,
185    pub rationale: String,
186    pub subjects: Vec<String>,
187    pub evidence_gaps: Vec<EvidenceGap>,
188}
189
190impl ControlFinding {
191    pub fn satisfied(
192        control_id: ControlId,
193        rationale: impl Into<String>,
194        subjects: Vec<String>,
195    ) -> Self {
196        Self {
197            control_id,
198            status: ControlStatus::Satisfied,
199            rationale: rationale.into(),
200            subjects,
201            evidence_gaps: Vec::new(),
202        }
203    }
204
205    pub fn violated(
206        control_id: ControlId,
207        rationale: impl Into<String>,
208        subjects: Vec<String>,
209    ) -> Self {
210        Self {
211            control_id,
212            status: ControlStatus::Violated,
213            rationale: rationale.into(),
214            subjects,
215            evidence_gaps: Vec::new(),
216        }
217    }
218
219    pub fn indeterminate(
220        control_id: ControlId,
221        rationale: impl Into<String>,
222        subjects: Vec<String>,
223        evidence_gaps: Vec<EvidenceGap>,
224    ) -> Self {
225        Self {
226            control_id,
227            status: ControlStatus::Indeterminate,
228            rationale: rationale.into(),
229            subjects,
230            evidence_gaps,
231        }
232    }
233
234    pub fn not_applicable(control_id: ControlId, rationale: impl Into<String>) -> Self {
235        Self {
236            control_id,
237            status: ControlStatus::NotApplicable,
238            rationale: rationale.into(),
239            subjects: Vec::new(),
240            evidence_gaps: Vec::new(),
241        }
242    }
243
244    /// Extracts `RepositoryPosture` from evidence, returning appropriate
245    /// `Indeterminate` or `NotApplicable` findings for non-complete states.
246    ///
247    /// Use in posture controls to eliminate repeated `match` boilerplate:
248    /// ```ignore
249    /// let posture = match ControlFinding::extract_posture(self.id(), evidence) {
250    ///     Ok(p) => p,
251    ///     Err(findings) => return findings,
252    /// };
253    /// ```
254    pub fn extract_posture(
255        id: ControlId,
256        evidence: &EvidenceBundle,
257    ) -> Result<&RepositoryPosture, Vec<ControlFinding>> {
258        match &evidence.repository_posture {
259            EvidenceState::Complete { value } | EvidenceState::Partial { value, .. } => Ok(value),
260            EvidenceState::Missing { gaps } => Err(vec![ControlFinding::indeterminate(
261                id,
262                "Repository posture evidence could not be collected",
263                vec![],
264                gaps.clone(),
265            )]),
266            EvidenceState::NotApplicable => Err(vec![ControlFinding::not_applicable(
267                id,
268                "Repository posture not applicable",
269            )]),
270        }
271    }
272}
273
274/// A verifiable SDLC control that produces findings from evidence.
275pub trait Control: Send + Sync {
276    /// Returns the unique identifier for this control.
277    fn id(&self) -> ControlId;
278
279    /// Human-readable description for SARIF rule output.
280    fn description(&self) -> &'static str {
281        "Custom control"
282    }
283
284    /// SOC2 Trust Services Criteria this control maps to (e.g., &["CC6.1", "CC8.1"]).
285    /// Returns empty slice for controls not mapped to SOC2.
286    fn tsc_criteria(&self) -> &'static [&'static str] {
287        builtin_tsc_mapping(self.id().as_str())
288    }
289
290    /// Evaluates the evidence bundle and returns one finding per subject.
291    fn evaluate(&self, evidence: &EvidenceBundle) -> Vec<ControlFinding>;
292}
293
294/// Returns SOC2 Trust Services Criteria for a built-in control ID.
295pub fn builtin_tsc_mapping(id: &str) -> &'static [&'static str] {
296    match id {
297        // CC6: Logical and Physical Access Controls
298        builtin::SOURCE_AUTHENTICITY => &["CC6.1"],
299        builtin::BRANCH_PROTECTION_ENFORCEMENT => &["CC6.1", "CC8.1"],
300        builtin::CODEOWNERS_COVERAGE => &["CC6.1"],
301        builtin::SECRET_SCANNING => &["CC6.1", "CC6.6"],
302        // CC7: System Operations
303        builtin::ISSUE_LINKAGE => &["CC7.2"],
304        builtin::STALE_REVIEW => &["CC7.2"],
305        builtin::SECURITY_FILE_CHANGE => &["CC7.2"],
306        builtin::RELEASE_TRACEABILITY => &["CC7.2"],
307        builtin::REQUIRED_STATUS_CHECKS => &["CC7.1"],
308        builtin::VULNERABILITY_SCANNING => &["CC7.1"],
309        builtin::SECURITY_POLICY => &["CC7.3", "CC7.4"],
310        // CC8: Change Management
311        builtin::REVIEW_INDEPENDENCE => &["CC8.1"],
312        builtin::TWO_PARTY_REVIEW => &["CC8.1"],
313        builtin::CHANGE_REQUEST_SIZE => &["CC8.1"],
314        builtin::TEST_COVERAGE => &["CC8.1"],
315        builtin::SCOPED_CHANGE => &["CC8.1"],
316        builtin::DESCRIPTION_QUALITY => &["CC8.1"],
317        builtin::MERGE_COMMIT_POLICY => &["CC8.1"],
318        builtin::CONVENTIONAL_TITLE => &["CC8.1"],
319        builtin::BRANCH_HISTORY_INTEGRITY => &["CC8.1"],
320        // PI: Processing Integrity
321        builtin::BUILD_PROVENANCE => &["PI1.4"],
322        builtin::HOSTED_BUILD_PLATFORM => &["PI1.4"],
323        builtin::PROVENANCE_AUTHENTICITY => &["PI1.4"],
324        builtin::BUILD_ISOLATION => &["PI1.4"],
325        // Dependencies (CC7.1 + PI)
326        builtin::DEPENDENCY_SIGNATURE => &["CC7.1", "PI1.4"],
327        builtin::DEPENDENCY_PROVENANCE_CHECK => &["CC7.1", "PI1.4"],
328        builtin::DEPENDENCY_SIGNER_VERIFIED => &["CC7.1", "PI1.4"],
329        builtin::DEPENDENCY_COMPLETENESS => &["CC7.1", "PI1.4"],
330        // Enterprise Posture
331        builtin::SECRET_SCANNING_PUSH_PROTECTION => &["CC6.1", "CC6.6"],
332        builtin::BRANCH_PROTECTION_ADMIN_ENFORCEMENT => &["CC6.1", "CC8.1"],
333        builtin::DISMISS_STALE_REVIEWS_ON_PUSH => &["CC8.1"],
334        builtin::ACTIONS_PINNED_DEPENDENCIES => &["CC7.1", "PI1.4"],
335        builtin::ENVIRONMENT_PROTECTION_RULES => &["CC6.1", "CC8.1"],
336        builtin::CODE_SCANNING_ALERTS_RESOLVED => &["CC7.1"],
337        builtin::DEPENDENCY_LICENSE_COMPLIANCE => &["CC7.1"],
338        builtin::SBOM_ATTESTATION => &["CC7.1"],
339        builtin::RELEASE_ASSET_ATTESTATION => &["PI1.4"],
340        builtin::PRIVILEGED_WORKFLOW_DETECTION => &["CC6.1", "CC8.1"],
341        _ => &[],
342    }
343}
344
345/// Runs every control against the evidence bundle and collects all findings.
346pub fn evaluate_all(
347    controls: &[Box<dyn Control>],
348    evidence: &EvidenceBundle,
349) -> Vec<ControlFinding> {
350    let mut findings = Vec::new();
351    for control in controls {
352        findings.extend(control.evaluate(evidence));
353    }
354    findings
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn control_id_display() {
363        let id = ControlId::new("review-independence");
364        assert_eq!(id.to_string(), "review-independence");
365        assert_eq!(id.as_str(), "review-independence");
366    }
367
368    #[test]
369    fn control_id_from_str() {
370        let id: ControlId = "source-authenticity".into();
371        assert_eq!(id.as_str(), "source-authenticity");
372    }
373
374    #[test]
375    fn builtin_ids_are_unique() {
376        let mut seen = std::collections::HashSet::new();
377        for id in builtin::ALL {
378            assert!(seen.insert(id), "duplicate built-in ID: {id}");
379        }
380    }
381}