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    /// Actionable remediation hint shown when the control fails or needs review.
297    fn remediation_hint(&self) -> Option<&'static str> {
298        builtin_remediation_hint(self.id().as_str())
299    }
300
301    /// Evaluates the evidence bundle and returns one finding per subject.
302    fn evaluate(&self, evidence: &EvidenceBundle) -> Vec<ControlFinding>;
303}
304
305/// Returns an actionable remediation hint for a built-in control ID.
306pub fn builtin_remediation_hint(id: &str) -> Option<&'static str> {
307    match id {
308        builtin::SOURCE_AUTHENTICITY => Some("Sign commits: git config commit.gpgsign true"),
309        builtin::REVIEW_INDEPENDENCE => {
310            Some("Ensure PRs are reviewed by someone other than the author")
311        }
312        builtin::BRANCH_HISTORY_INTEGRITY => {
313            Some("Use linear history (rebase/squash, avoid merge commits)")
314        }
315        builtin::BRANCH_PROTECTION_ENFORCEMENT => {
316            Some("Enable branch protection rules at Settings > Branches")
317        }
318        builtin::TWO_PARTY_REVIEW => {
319            Some("Require at least 2 reviewers in branch protection rules")
320        }
321        builtin::REQUIRED_STATUS_CHECKS => {
322            Some("Add required status checks in branch protection rules")
323        }
324        builtin::BUILD_PROVENANCE => {
325            Some("Generate SLSA provenance with slsa-framework/slsa-github-generator")
326        }
327        builtin::HOSTED_BUILD_PLATFORM => Some("Use GitHub-hosted runners instead of self-hosted"),
328        builtin::PROVENANCE_AUTHENTICITY => {
329            Some("Verify build provenance signatures with cosign/slsa-verifier")
330        }
331        builtin::BUILD_ISOLATION => Some("Ensure builds run in ephemeral, isolated environments"),
332        builtin::DEPENDENCY_SIGNATURE => {
333            Some("Use signed dependencies; verify with cosign or sigstore")
334        }
335        builtin::DEPENDENCY_PROVENANCE_CHECK => {
336            Some("Ensure dependencies publish SLSA provenance attestations")
337        }
338        builtin::DEPENDENCY_SIGNER_VERIFIED => {
339            Some("Verify dependency signers against a trusted list")
340        }
341        builtin::DEPENDENCY_COMPLETENESS => {
342            Some("Ensure all transitive dependencies have provenance")
343        }
344        builtin::CHANGE_REQUEST_SIZE => Some(
345            "Keep PRs small and focused; split large changes. Monorepo cross-package PRs may false-positive here -- use --exclude change-request-size",
346        ),
347        builtin::TEST_COVERAGE => Some(
348            "Add or update tests for changed source files. Dependency-only PRs may false-positive here -- use --exclude test-coverage",
349        ),
350        builtin::SCOPED_CHANGE => Some(
351            "Limit PR to a single logical change; split unrelated changes. In monorepos, features spanning multiple packages are expected -- use --exclude scoped-change",
352        ),
353        builtin::ISSUE_LINKAGE => Some(
354            "Reference an issue in the PR body: Fixes #123 or Closes #456. Bot PRs (Dependabot/Renovate) don't link issues -- use --exclude issue-linkage",
355        ),
356        builtin::DESCRIPTION_QUALITY => {
357            Some("Add a meaningful PR description explaining the change")
358        }
359        builtin::MERGE_COMMIT_POLICY => {
360            Some("Use squash or rebase merge strategy instead of merge commits")
361        }
362        builtin::CONVENTIONAL_TITLE => Some(
363            "Use Conventional Commits format: type(scope): description. Bot PRs use their own title format -- use --exclude conventional-title",
364        ),
365        builtin::STALE_REVIEW => Some("Re-request review if changes were pushed after approval"),
366        builtin::SECURITY_FILE_CHANGE => {
367            Some("Security-sensitive file changes require additional review")
368        }
369        builtin::RELEASE_TRACEABILITY => Some("Link release to merged PRs and resolved issues"),
370        builtin::CODEOWNERS_COVERAGE => Some("Add a CODEOWNERS file to define code ownership"),
371        builtin::SECRET_SCANNING => {
372            Some("Enable secret scanning at Settings > Code security and analysis")
373        }
374        builtin::VULNERABILITY_SCANNING => {
375            Some("Enable Dependabot alerts at Settings > Code security and analysis")
376        }
377        builtin::SECURITY_POLICY => {
378            Some("Add a SECURITY.md file with vulnerability reporting instructions")
379        }
380        builtin::SECRET_SCANNING_PUSH_PROTECTION => {
381            Some("Enable push protection at Settings > Code security > Secret scanning")
382        }
383        builtin::BRANCH_PROTECTION_ADMIN_ENFORCEMENT => {
384            Some("Enable 'Include administrators' in branch protection rules")
385        }
386        builtin::DISMISS_STALE_REVIEWS_ON_PUSH => {
387            Some("Enable 'Dismiss stale pull request approvals when new commits are pushed'")
388        }
389        builtin::ACTIONS_PINNED_DEPENDENCIES => {
390            Some("Pin GitHub Actions to full commit SHAs instead of tags")
391        }
392        builtin::ENVIRONMENT_PROTECTION_RULES => {
393            Some("Configure environment protection rules at Settings > Environments")
394        }
395        builtin::CODE_SCANNING_ALERTS_RESOLVED => {
396            Some("Resolve open code scanning alerts at Security > Code scanning alerts")
397        }
398        builtin::DEPENDENCY_LICENSE_COMPLIANCE => {
399            Some("Review dependency licenses; remove or replace copyleft dependencies")
400        }
401        builtin::SBOM_ATTESTATION => {
402            Some("Generate SBOM with gh attestation or anchore/sbom-action in CI")
403        }
404        builtin::RELEASE_ASSET_ATTESTATION => {
405            Some("Attest release assets with gh attestation or sigstore/cosign")
406        }
407        builtin::PRIVILEGED_WORKFLOW_DETECTION => {
408            Some("Avoid pull_request_target with checkout of PR code in workflows")
409        }
410        builtin::WORKFLOW_PERMISSIONS_RESTRICTED => {
411            Some("Set default workflow permissions to 'Read' at Settings > Actions > General")
412        }
413        builtin::DEPENDENCY_UPDATE_TOOL => Some(
414            "Add .github/dependabot.yml or renovate.json to enable automated dependency updates",
415        ),
416        builtin::REPOSITORY_PERMISSIONS_AUDIT => {
417            Some("Reduce admin count (<= 3), use team-based access instead of direct collaborators")
418        }
419        builtin::DEFAULT_BRANCH_SETTINGS_BASELINE => Some(
420            "Enable branch protection, admin enforcement, and stale review dismissal on default branch",
421        ),
422        builtin::SECURITY_TEST_IN_CI => {
423            Some("Add CodeQL or Semgrep to GitHub Actions: github/codeql-action/analyze")
424        }
425        builtin::PROTECTED_TAGS => {
426            Some("Add tag protection rules at Settings > Tags to prevent unauthorized releases")
427        }
428        _ => None,
429    }
430}
431
432/// Returns SOC2 Trust Services Criteria for a built-in control ID.
433pub fn builtin_tsc_mapping(id: &str) -> &'static [&'static str] {
434    match id {
435        // CC6: Logical and Physical Access Controls
436        builtin::SOURCE_AUTHENTICITY => &["CC6.1"],
437        builtin::BRANCH_PROTECTION_ENFORCEMENT => &["CC6.1", "CC8.1"],
438        builtin::CODEOWNERS_COVERAGE => &["CC6.1"],
439        builtin::SECRET_SCANNING => &["CC6.1", "CC6.6"],
440        // CC7: System Operations
441        builtin::ISSUE_LINKAGE => &["CC7.2"],
442        builtin::STALE_REVIEW => &["CC7.2"],
443        builtin::SECURITY_FILE_CHANGE => &["CC7.2"],
444        builtin::RELEASE_TRACEABILITY => &["CC7.2"],
445        builtin::REQUIRED_STATUS_CHECKS => &["CC7.1"],
446        builtin::VULNERABILITY_SCANNING => &["CC7.1"],
447        builtin::SECURITY_POLICY => &["CC7.3", "CC7.4"],
448        // CC8: Change Management
449        builtin::REVIEW_INDEPENDENCE => &["CC8.1"],
450        builtin::TWO_PARTY_REVIEW => &["CC8.1"],
451        builtin::CHANGE_REQUEST_SIZE => &["CC8.1"],
452        builtin::TEST_COVERAGE => &["CC8.1"],
453        builtin::SCOPED_CHANGE => &["CC8.1"],
454        builtin::DESCRIPTION_QUALITY => &["CC8.1"],
455        builtin::MERGE_COMMIT_POLICY => &["CC8.1"],
456        builtin::CONVENTIONAL_TITLE => &["CC8.1"],
457        builtin::BRANCH_HISTORY_INTEGRITY => &["CC8.1"],
458        // PI: Processing Integrity
459        builtin::BUILD_PROVENANCE => &["PI1.4"],
460        builtin::HOSTED_BUILD_PLATFORM => &["PI1.4"],
461        builtin::PROVENANCE_AUTHENTICITY => &["PI1.4"],
462        builtin::BUILD_ISOLATION => &["PI1.4"],
463        // Dependencies (CC7.1 + PI)
464        builtin::DEPENDENCY_SIGNATURE => &["CC7.1", "PI1.4"],
465        builtin::DEPENDENCY_PROVENANCE_CHECK => &["CC7.1", "PI1.4"],
466        builtin::DEPENDENCY_SIGNER_VERIFIED => &["CC7.1", "PI1.4"],
467        builtin::DEPENDENCY_COMPLETENESS => &["CC7.1", "PI1.4"],
468        // Enterprise Posture
469        builtin::SECRET_SCANNING_PUSH_PROTECTION => &["CC6.1", "CC6.6"],
470        builtin::BRANCH_PROTECTION_ADMIN_ENFORCEMENT => &["CC6.1", "CC8.1"],
471        builtin::DISMISS_STALE_REVIEWS_ON_PUSH => &["CC8.1"],
472        builtin::ACTIONS_PINNED_DEPENDENCIES => &["CC7.1", "PI1.4"],
473        builtin::ENVIRONMENT_PROTECTION_RULES => &["CC6.1", "CC8.1"],
474        builtin::CODE_SCANNING_ALERTS_RESOLVED => &["CC7.1"],
475        builtin::DEPENDENCY_LICENSE_COMPLIANCE => &["CC7.1"],
476        builtin::SBOM_ATTESTATION => &["CC7.1"],
477        builtin::RELEASE_ASSET_ATTESTATION => &["PI1.4"],
478        builtin::PRIVILEGED_WORKFLOW_DETECTION => &["CC6.1", "CC8.1"],
479        _ => &[],
480    }
481}
482
483/// Runs every control against the evidence bundle and collects all findings.
484pub fn evaluate_all(
485    controls: &[Box<dyn Control>],
486    evidence: &EvidenceBundle,
487) -> Vec<ControlFinding> {
488    let mut findings = Vec::new();
489    for control in controls {
490        findings.extend(control.evaluate(evidence));
491    }
492    findings
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    #[test]
500    fn control_id_display() {
501        let id = ControlId::new("review-independence");
502        assert_eq!(id.to_string(), "review-independence");
503        assert_eq!(id.as_str(), "review-independence");
504    }
505
506    #[test]
507    fn control_id_from_str() {
508        let id: ControlId = "source-authenticity".into();
509        assert_eq!(id.as_str(), "source-authenticity");
510    }
511
512    #[test]
513    fn all_builtins_have_remediation_hints() {
514        for id in builtin::ALL {
515            assert!(
516                builtin_remediation_hint(id).is_some(),
517                "missing remediation hint for built-in control: {id}"
518            );
519        }
520    }
521
522    #[test]
523    fn builtin_ids_are_unique() {
524        let mut seen = std::collections::HashSet::new();
525        for id in builtin::ALL {
526            assert!(seen.insert(id), "duplicate built-in ID: {id}");
527        }
528    }
529}