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
99    /// All 38 built-in control IDs.
100    pub const ALL: &[&str] = &[
101        SOURCE_AUTHENTICITY,
102        REVIEW_INDEPENDENCE,
103        BRANCH_HISTORY_INTEGRITY,
104        BRANCH_PROTECTION_ENFORCEMENT,
105        TWO_PARTY_REVIEW,
106        BUILD_PROVENANCE,
107        REQUIRED_STATUS_CHECKS,
108        HOSTED_BUILD_PLATFORM,
109        PROVENANCE_AUTHENTICITY,
110        BUILD_ISOLATION,
111        DEPENDENCY_SIGNATURE,
112        DEPENDENCY_PROVENANCE_CHECK,
113        DEPENDENCY_SIGNER_VERIFIED,
114        DEPENDENCY_COMPLETENESS,
115        CHANGE_REQUEST_SIZE,
116        TEST_COVERAGE,
117        SCOPED_CHANGE,
118        ISSUE_LINKAGE,
119        STALE_REVIEW,
120        DESCRIPTION_QUALITY,
121        MERGE_COMMIT_POLICY,
122        CONVENTIONAL_TITLE,
123        SECURITY_FILE_CHANGE,
124        RELEASE_TRACEABILITY,
125        CODEOWNERS_COVERAGE,
126        SECRET_SCANNING,
127        VULNERABILITY_SCANNING,
128        SECURITY_POLICY,
129        SECRET_SCANNING_PUSH_PROTECTION,
130        BRANCH_PROTECTION_ADMIN_ENFORCEMENT,
131        DISMISS_STALE_REVIEWS_ON_PUSH,
132        ACTIONS_PINNED_DEPENDENCIES,
133        ENVIRONMENT_PROTECTION_RULES,
134        CODE_SCANNING_ALERTS_RESOLVED,
135        DEPENDENCY_LICENSE_COMPLIANCE,
136        SBOM_ATTESTATION,
137        RELEASE_ASSET_ATTESTATION,
138        PRIVILEGED_WORKFLOW_DETECTION,
139    ];
140
141    /// Returns a ControlId for a built-in constant.
142    pub fn id(s: &str) -> ControlId {
143        ControlId::new(s)
144    }
145}
146
147/// Outcome of evaluating a single control against evidence.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "snake_case")]
150pub enum ControlStatus {
151    Satisfied,
152    Violated,
153    Indeterminate,
154    NotApplicable,
155}
156
157impl ControlStatus {
158    pub fn as_str(&self) -> &'static str {
159        match self {
160            Self::Satisfied => "satisfied",
161            Self::Violated => "violated",
162            Self::Indeterminate => "indeterminate",
163            Self::NotApplicable => "not_applicable",
164        }
165    }
166}
167
168impl fmt::Display for ControlStatus {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        f.write_str(self.as_str())
171    }
172}
173
174/// Result of a single control evaluation.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct ControlFinding {
177    pub control_id: ControlId,
178    pub status: ControlStatus,
179    pub rationale: String,
180    pub subjects: Vec<String>,
181    pub evidence_gaps: Vec<EvidenceGap>,
182}
183
184impl ControlFinding {
185    pub fn satisfied(
186        control_id: ControlId,
187        rationale: impl Into<String>,
188        subjects: Vec<String>,
189    ) -> Self {
190        Self {
191            control_id,
192            status: ControlStatus::Satisfied,
193            rationale: rationale.into(),
194            subjects,
195            evidence_gaps: Vec::new(),
196        }
197    }
198
199    pub fn violated(
200        control_id: ControlId,
201        rationale: impl Into<String>,
202        subjects: Vec<String>,
203    ) -> Self {
204        Self {
205            control_id,
206            status: ControlStatus::Violated,
207            rationale: rationale.into(),
208            subjects,
209            evidence_gaps: Vec::new(),
210        }
211    }
212
213    pub fn indeterminate(
214        control_id: ControlId,
215        rationale: impl Into<String>,
216        subjects: Vec<String>,
217        evidence_gaps: Vec<EvidenceGap>,
218    ) -> Self {
219        Self {
220            control_id,
221            status: ControlStatus::Indeterminate,
222            rationale: rationale.into(),
223            subjects,
224            evidence_gaps,
225        }
226    }
227
228    pub fn not_applicable(control_id: ControlId, rationale: impl Into<String>) -> Self {
229        Self {
230            control_id,
231            status: ControlStatus::NotApplicable,
232            rationale: rationale.into(),
233            subjects: Vec::new(),
234            evidence_gaps: Vec::new(),
235        }
236    }
237
238    /// Extracts `RepositoryPosture` from evidence, returning appropriate
239    /// `Indeterminate` or `NotApplicable` findings for non-complete states.
240    ///
241    /// Use in posture controls to eliminate repeated `match` boilerplate:
242    /// ```ignore
243    /// let posture = match ControlFinding::extract_posture(self.id(), evidence) {
244    ///     Ok(p) => p,
245    ///     Err(findings) => return findings,
246    /// };
247    /// ```
248    pub fn extract_posture(
249        id: ControlId,
250        evidence: &EvidenceBundle,
251    ) -> Result<&RepositoryPosture, Vec<ControlFinding>> {
252        match &evidence.repository_posture {
253            EvidenceState::Complete { value } | EvidenceState::Partial { value, .. } => Ok(value),
254            EvidenceState::Missing { gaps } => Err(vec![ControlFinding::indeterminate(
255                id,
256                "Repository posture evidence could not be collected",
257                vec![],
258                gaps.clone(),
259            )]),
260            EvidenceState::NotApplicable => Err(vec![ControlFinding::not_applicable(
261                id,
262                "Repository posture not applicable",
263            )]),
264        }
265    }
266}
267
268/// A verifiable SDLC control that produces findings from evidence.
269pub trait Control: Send + Sync {
270    /// Returns the unique identifier for this control.
271    fn id(&self) -> ControlId;
272
273    /// Human-readable description for SARIF rule output.
274    fn description(&self) -> &'static str {
275        "Custom control"
276    }
277
278    /// SOC2 Trust Services Criteria this control maps to (e.g., &["CC6.1", "CC8.1"]).
279    /// Returns empty slice for controls not mapped to SOC2.
280    fn tsc_criteria(&self) -> &'static [&'static str] {
281        builtin_tsc_mapping(self.id().as_str())
282    }
283
284    /// Evaluates the evidence bundle and returns one finding per subject.
285    fn evaluate(&self, evidence: &EvidenceBundle) -> Vec<ControlFinding>;
286}
287
288/// Returns SOC2 Trust Services Criteria for a built-in control ID.
289pub fn builtin_tsc_mapping(id: &str) -> &'static [&'static str] {
290    match id {
291        // CC6: Logical and Physical Access Controls
292        builtin::SOURCE_AUTHENTICITY => &["CC6.1"],
293        builtin::BRANCH_PROTECTION_ENFORCEMENT => &["CC6.1", "CC8.1"],
294        builtin::CODEOWNERS_COVERAGE => &["CC6.1"],
295        builtin::SECRET_SCANNING => &["CC6.1", "CC6.6"],
296        // CC7: System Operations
297        builtin::ISSUE_LINKAGE => &["CC7.2"],
298        builtin::STALE_REVIEW => &["CC7.2"],
299        builtin::SECURITY_FILE_CHANGE => &["CC7.2"],
300        builtin::RELEASE_TRACEABILITY => &["CC7.2"],
301        builtin::REQUIRED_STATUS_CHECKS => &["CC7.1"],
302        builtin::VULNERABILITY_SCANNING => &["CC7.1"],
303        builtin::SECURITY_POLICY => &["CC7.3", "CC7.4"],
304        // CC8: Change Management
305        builtin::REVIEW_INDEPENDENCE => &["CC8.1"],
306        builtin::TWO_PARTY_REVIEW => &["CC8.1"],
307        builtin::CHANGE_REQUEST_SIZE => &["CC8.1"],
308        builtin::TEST_COVERAGE => &["CC8.1"],
309        builtin::SCOPED_CHANGE => &["CC8.1"],
310        builtin::DESCRIPTION_QUALITY => &["CC8.1"],
311        builtin::MERGE_COMMIT_POLICY => &["CC8.1"],
312        builtin::CONVENTIONAL_TITLE => &["CC8.1"],
313        builtin::BRANCH_HISTORY_INTEGRITY => &["CC8.1"],
314        // PI: Processing Integrity
315        builtin::BUILD_PROVENANCE => &["PI1.4"],
316        builtin::HOSTED_BUILD_PLATFORM => &["PI1.4"],
317        builtin::PROVENANCE_AUTHENTICITY => &["PI1.4"],
318        builtin::BUILD_ISOLATION => &["PI1.4"],
319        // Dependencies (CC7.1 + PI)
320        builtin::DEPENDENCY_SIGNATURE => &["CC7.1", "PI1.4"],
321        builtin::DEPENDENCY_PROVENANCE_CHECK => &["CC7.1", "PI1.4"],
322        builtin::DEPENDENCY_SIGNER_VERIFIED => &["CC7.1", "PI1.4"],
323        builtin::DEPENDENCY_COMPLETENESS => &["CC7.1", "PI1.4"],
324        // Enterprise Posture
325        builtin::SECRET_SCANNING_PUSH_PROTECTION => &["CC6.1", "CC6.6"],
326        builtin::BRANCH_PROTECTION_ADMIN_ENFORCEMENT => &["CC6.1", "CC8.1"],
327        builtin::DISMISS_STALE_REVIEWS_ON_PUSH => &["CC8.1"],
328        builtin::ACTIONS_PINNED_DEPENDENCIES => &["CC7.1", "PI1.4"],
329        builtin::ENVIRONMENT_PROTECTION_RULES => &["CC6.1", "CC8.1"],
330        builtin::CODE_SCANNING_ALERTS_RESOLVED => &["CC7.1"],
331        builtin::DEPENDENCY_LICENSE_COMPLIANCE => &["CC7.1"],
332        builtin::SBOM_ATTESTATION => &["CC7.1"],
333        builtin::RELEASE_ASSET_ATTESTATION => &["PI1.4"],
334        builtin::PRIVILEGED_WORKFLOW_DETECTION => &["CC6.1", "CC8.1"],
335        _ => &[],
336    }
337}
338
339/// Runs every control against the evidence bundle and collects all findings.
340pub fn evaluate_all(
341    controls: &[Box<dyn Control>],
342    evidence: &EvidenceBundle,
343) -> Vec<ControlFinding> {
344    let mut findings = Vec::new();
345    for control in controls {
346        findings.extend(control.evaluate(evidence));
347    }
348    findings
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn control_id_display() {
357        let id = ControlId::new("review-independence");
358        assert_eq!(id.to_string(), "review-independence");
359        assert_eq!(id.as_str(), "review-independence");
360    }
361
362    #[test]
363    fn control_id_from_str() {
364        let id: ControlId = "source-authenticity".into();
365        assert_eq!(id.as_str(), "source-authenticity");
366    }
367
368    #[test]
369    fn builtin_ids_are_unique() {
370        let mut seen = std::collections::HashSet::new();
371        for id in builtin::ALL {
372            assert!(seen.insert(id), "duplicate built-in ID: {id}");
373        }
374    }
375}