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