Skip to main content

cellos_evidence/
lib.rs

1//! Accreditation evidence library (S42/S43/S44, ADR-0032).
2//!
3//! This crate turns the hand-authored control-mapping catalog
4//! (`contracts/controls/cellos-800-53-rev5-mapping.json`) into machine-checked,
5//! deterministically-emitted accreditation evidence. It does three things:
6//!
7//! 1. **Load + lint (S43).** [`load_catalog`] parses the catalog and
8//!    [`lint_catalog`] asserts every entry validates against the
9//!    control-mapping schema, that every `codeSeams`/`provingTests` path
10//!    resolves on disk, that `status: implemented` entries carry non-empty
11//!    proving event types and tests, and that a `linux-nftables` +
12//!    `implemented` entry carries a `degradedBindingNote`.
13//! 2. **Emit (S44).** [`emit_oscal`] produces an OSCAL-style
14//!    component-definition + SSP fragment ([`EvidencePackage`]) where every
15//!    implemented requirement carries machine-embedded remarks that this is a
16//!    *candidate*, not an assessor-verified satisfaction. SC-13/IA-7 carry an
17//!    explicit "crypto module NOT CMVP-validated" remark; `linux-nftables`
18//!    entries carry a platform-scope remark.
19//!
20//! ## Honesty invariants
21//!
22//! The catalog is **candidate evidence** an operator hands to an assessor, not
23//! a self-attestation of satisfaction (mirrors how a cortex receipt is a
24//! candidate, never a direct admission). The emitter therefore stamps every
25//! implemented requirement with `candidate, not assessor-verified` and refuses
26//! to silently upgrade `algorithm-present-not-validated` (SC-13/IA-7) into a
27//! validated claim.
28//!
29//! ## Determinism
30//!
31//! [`emit_oscal`] is a pure function of the catalog bytes: entries are emitted
32//! in catalog order and every map is a `BTreeMap`/ordered `Vec`, so two emit
33//! runs are byte-identical. This is asserted by the crate tests.
34
35use std::collections::BTreeMap;
36use std::path::{Path, PathBuf};
37
38use serde::{Deserialize, Serialize};
39
40pub mod rollup;
41mod schema;
42pub mod sign;
43
44pub use rollup::{rollup, ControlCoverage, RollupReport};
45pub use schema::{control_mapping_schema_json, validate_entry, SchemaError};
46pub use sign::{sign_evidence_package, verify_evidence_package, EVIDENCE_PACKAGE_TYPE};
47
48/// Repo-relative path to the canonical control-mapping catalog (S42).
49pub const CATALOG_RELPATH: &str = "contracts/controls/cellos-800-53-rev5-mapping.json";
50
51/// Repo-relative path to the control-mapping JSON Schema (S41).
52pub const SCHEMA_RELPATH: &str = "contracts/schemas/control-mapping-v1.schema.json";
53
54/// Machine-embedded remark stamped on every emitted implemented requirement.
55pub const CANDIDATE_REMARK: &str = "candidate, not assessor-verified";
56
57/// Machine-embedded remark for SC-13/IA-7 (algorithm-present-not-validated).
58pub const CRYPTO_NOT_VALIDATED_REMARK: &str = "crypto module NOT CMVP-validated";
59
60/// One control-mapping catalog entry. Field shape mirrors
61/// `control-mapping-v1.schema.json`; `#[serde(rename_all = "camelCase")]`
62/// keeps the on-disk JSON keys identical to the schema.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct ControlMappingEntry {
66    /// 800-53 Rev5 control id, e.g. `AU-10`, `AC-4`, `SC-13(1)`.
67    pub control_id: String,
68    /// Honest implementation status (see schema enum).
69    pub status: String,
70    /// Enforcement binding. Defaults to `n/a` when omitted in JSON.
71    #[serde(default = "default_binding")]
72    pub enforcement_binding: String,
73    /// `file` or `file:line` pointers to the implementing seams.
74    #[serde(default)]
75    pub code_seams: Vec<String>,
76    /// Reverse-DNS CloudEvent type URNs evidencing the control.
77    #[serde(default)]
78    pub proving_event_types: Vec<String>,
79    /// Test paths exercising the control.
80    #[serde(default)]
81    pub proving_tests: Vec<String>,
82    /// Human-legible implementation statement for the SSP fragment.
83    pub narrative: String,
84    /// REQUIRED when `enforcementBinding=linux-nftables` and
85    /// `status=implemented`.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub degraded_binding_note: Option<String>,
88    /// Optional cross-framework references.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub crosswalk: Option<serde_json::Value>,
91}
92
93fn default_binding() -> String {
94    "n/a".to_string()
95}
96
97impl ControlMappingEntry {
98    /// `true` if this entry claims `status: implemented`.
99    #[must_use]
100    pub fn is_implemented(&self) -> bool {
101        self.status == "implemented"
102    }
103
104    /// `true` if this entry is kernel-bound to `linux-nftables`.
105    #[must_use]
106    pub fn is_nftables_bound(&self) -> bool {
107        self.enforcement_binding == "linux-nftables"
108    }
109
110    /// `true` for the deliberately-honest crypto state SC-13/IA-7 live in.
111    #[must_use]
112    pub fn is_algorithm_present_not_validated(&self) -> bool {
113        self.status == "algorithm-present-not-validated"
114    }
115}
116
117/// Errors raised while loading or linting the catalog.
118#[derive(Debug, thiserror::Error)]
119pub enum EvidenceError {
120    /// The catalog or schema file could not be read.
121    #[error("io error reading {path}: {source}")]
122    Io {
123        /// The path that failed to read.
124        path: String,
125        /// The underlying io error.
126        source: std::io::Error,
127    },
128    /// The catalog was not valid JSON / did not deserialize.
129    #[error("catalog parse error: {0}")]
130    Parse(#[from] serde_json::Error),
131    /// One or more lint findings. Each string is a self-contained finding.
132    #[error("catalog lint failed with {} finding(s):\n  - {}", .0.len(), .0.join("\n  - "))]
133    Lint(Vec<String>),
134    /// Schema compilation/usage failed.
135    #[error("schema error: {0}")]
136    Schema(#[from] SchemaError),
137}
138
139/// Resolve the repo root from this crate's manifest dir
140/// (`<root>/crates/cellos-evidence`).
141#[must_use]
142pub fn repo_root() -> PathBuf {
143    let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
144    manifest
145        .parent()
146        .and_then(Path::parent)
147        .map_or_else(|| manifest.to_path_buf(), Path::to_path_buf)
148}
149
150/// Load and parse the control-mapping catalog under `root`.
151///
152/// # Errors
153/// Returns [`EvidenceError::Io`] if the file cannot be read and
154/// [`EvidenceError::Parse`] if it does not deserialize.
155pub fn load_catalog(root: &Path) -> Result<Vec<ControlMappingEntry>, EvidenceError> {
156    let path = root.join(CATALOG_RELPATH);
157    let bytes = std::fs::read(&path).map_err(|source| EvidenceError::Io {
158        path: path.display().to_string(),
159        source,
160    })?;
161    let entries: Vec<ControlMappingEntry> = serde_json::from_slice(&bytes)?;
162    Ok(entries)
163}
164
165/// Load the raw catalog JSON values (schema-validated against the *exact*
166/// on-disk shape, not the deserialized struct). Used by the linter so that
167/// schema violations surface as schema errors rather than parse errors.
168///
169/// # Errors
170/// Returns [`EvidenceError::Io`]/[`EvidenceError::Parse`] on read/parse failure.
171pub fn load_catalog_values(root: &Path) -> Result<Vec<serde_json::Value>, EvidenceError> {
172    let path = root.join(CATALOG_RELPATH);
173    let bytes = std::fs::read(&path).map_err(|source| EvidenceError::Io {
174        path: path.display().to_string(),
175        source,
176    })?;
177    let values: Vec<serde_json::Value> = serde_json::from_slice(&bytes)?;
178    Ok(values)
179}
180
181/// Lint the catalog (S43).
182///
183/// Asserts, for the catalog under `root`:
184/// - every entry validates against the control-mapping schema;
185/// - every `codeSeams` / `provingTests` path resolves on disk (relative to
186///   `root`, allowing an optional `:line` suffix on seams);
187/// - `status: implemented` requires non-empty `provingEventTypes` AND
188///   non-empty `provingTests`;
189/// - `enforcementBinding=linux-nftables` + `status=implemented` carries a
190///   non-empty `degradedBindingNote`.
191///
192/// # Errors
193/// Returns [`EvidenceError::Lint`] carrying every finding (the linter collects
194/// all findings rather than failing on the first).
195pub fn lint_catalog(root: &Path) -> Result<Vec<ControlMappingEntry>, EvidenceError> {
196    let raw = load_catalog_values(root)?;
197    let entries = load_catalog(root)?;
198    let mut findings: Vec<String> = Vec::new();
199
200    let validator = schema::compile_validator(root)?;
201
202    for (i, value) in raw.iter().enumerate() {
203        let label = value
204            .get("controlId")
205            .and_then(serde_json::Value::as_str)
206            .map_or_else(|| format!("entry[{i}]"), |s| s.to_string());
207
208        // 1. Schema validation against the on-disk shape.
209        for msg in schema::validation_errors(&validator, value) {
210            findings.push(format!("{label}: schema violation: {msg}"));
211        }
212    }
213
214    for entry in &entries {
215        let label = &entry.control_id;
216
217        // 2. Seam + test paths must resolve on disk.
218        for seam in &entry.code_seams {
219            let rel = seam.split(':').next().unwrap_or(seam);
220            if !root.join(rel).exists() {
221                findings.push(format!("{label}: codeSeams path does not resolve: {seam}"));
222            }
223        }
224        for test in &entry.proving_tests {
225            let rel = test.split(':').next().unwrap_or(test);
226            if !root.join(rel).exists() {
227                findings.push(format!(
228                    "{label}: provingTests path does not resolve: {test}"
229                ));
230            }
231        }
232
233        // 3. implemented => non-empty proving event types + tests.
234        if entry.is_implemented() {
235            if entry.proving_event_types.is_empty() {
236                findings.push(format!(
237                    "{label}: status=implemented requires non-empty provingEventTypes"
238                ));
239            }
240            if entry.proving_tests.is_empty() {
241                findings.push(format!(
242                    "{label}: status=implemented requires non-empty provingTests"
243                ));
244            }
245        }
246
247        // 4. linux-nftables + implemented => degradedBindingNote present.
248        if entry.is_nftables_bound() && entry.is_implemented() {
249            let ok = entry
250                .degraded_binding_note
251                .as_ref()
252                .is_some_and(|n| !n.trim().is_empty());
253            if !ok {
254                findings.push(format!(
255                    "{label}: enforcementBinding=linux-nftables + status=implemented requires degradedBindingNote"
256                ));
257            }
258        }
259    }
260
261    if findings.is_empty() {
262        Ok(entries)
263    } else {
264        Err(EvidenceError::Lint(findings))
265    }
266}
267
268// ---------------------------------------------------------------------------
269// S44 — deterministic OSCAL-style emitter.
270// ---------------------------------------------------------------------------
271
272/// The full deterministic evidence package: a component-definition and an
273/// SSP fragment. Serialized with `serde_json` in catalog order.
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275pub struct EvidencePackage {
276    /// OSCAL-style component-definition fragment.
277    #[serde(rename = "component-definition")]
278    pub component_definition: ComponentDefinition,
279    /// OSCAL-style system-security-plan fragment.
280    #[serde(rename = "ssp-fragment")]
281    pub ssp_fragment: SspFragment,
282}
283
284/// OSCAL-style component-definition fragment.
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286pub struct ComponentDefinition {
287    /// Metadata block (title, disclaimer).
288    pub metadata: Metadata,
289    /// The single CellOS component with its control implementations.
290    pub components: Vec<Component>,
291}
292
293/// OSCAL-style SSP fragment.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295pub struct SspFragment {
296    /// Metadata block (title, disclaimer).
297    pub metadata: Metadata,
298    /// One implemented-requirement per catalog entry, in catalog order.
299    #[serde(rename = "implemented-requirements")]
300    pub implemented_requirements: Vec<ImplementedRequirement>,
301}
302
303/// Metadata block shared by both fragments.
304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305pub struct Metadata {
306    /// Human title.
307    pub title: String,
308    /// OSCAL-ish version of the emitting catalog format.
309    pub version: String,
310    /// Standing disclaimer: candidate evidence, never a self-attestation.
311    pub remarks: String,
312}
313
314/// One component (the CellOS substrate) carrying control implementations.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct Component {
317    /// Stable component id.
318    pub uuid: String,
319    /// Component type (software).
320    #[serde(rename = "type")]
321    pub component_type: String,
322    /// Component title.
323    pub title: String,
324    /// Control implementations, in catalog order.
325    #[serde(rename = "control-implementations")]
326    pub control_implementations: Vec<ControlImplementation>,
327}
328
329/// One control implementation entry (component-definition side).
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331pub struct ControlImplementation {
332    /// 800-53 control id.
333    #[serde(rename = "control-id")]
334    pub control_id: String,
335    /// Honest status (verbatim from the catalog).
336    pub status: String,
337    /// Enforcement binding.
338    #[serde(rename = "enforcement-binding")]
339    pub enforcement_binding: String,
340    /// Implementation narrative.
341    pub description: String,
342    /// Properties (codeSeams / provingEventTypes / provingTests), ordered.
343    pub props: BTreeMap<String, Vec<String>>,
344    /// Machine-embedded remarks (candidacy, crypto, platform scope).
345    pub remarks: Vec<String>,
346}
347
348/// One implemented-requirement (SSP side).
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350pub struct ImplementedRequirement {
351    /// 800-53 control id.
352    #[serde(rename = "control-id")]
353    pub control_id: String,
354    /// Honest status (verbatim from the catalog).
355    pub status: String,
356    /// Implementation narrative.
357    pub description: String,
358    /// Machine-embedded remarks (candidacy, crypto, platform scope).
359    pub remarks: Vec<String>,
360}
361
362/// Standing disclaimer stamped into every emitted fragment's metadata.
363const PACKAGE_DISCLAIMER: &str =
364    "Candidate accreditation evidence assembled from the CellOS control-mapping catalog. \
365     Every implemented claim is candidate, not assessor-verified. This is not a \
366     self-attestation of control satisfaction.";
367
368/// Build the machine-embedded remarks for one catalog entry.
369///
370/// Determinism: the order is fixed — candidacy first, then crypto (if
371/// applicable), then platform scope (if applicable).
372fn remarks_for(entry: &ControlMappingEntry) -> Vec<String> {
373    let mut remarks = Vec::new();
374    // Candidacy remark on every implemented (or implemented-shaped) requirement.
375    remarks.push(CANDIDATE_REMARK.to_string());
376    // SC-13 / IA-7: crypto module is NOT CMVP-validated.
377    if entry.is_algorithm_present_not_validated() {
378        remarks.push(CRYPTO_NOT_VALIDATED_REMARK.to_string());
379    }
380    // linux-nftables: platform-scope remark.
381    if entry.is_nftables_bound() {
382        let note = entry.degraded_binding_note.clone().unwrap_or_else(|| {
383            "Enforcement is kernel-bound on Linux+nftables only; elsewhere it degrades to declared-audit."
384                .to_string()
385        });
386        remarks.push(format!("platform-scope: {note}"));
387    }
388    remarks
389}
390
391/// Deterministically emit the OSCAL-style evidence package from the catalog
392/// (S44). Pure function of `entries` — emits in catalog order with ordered
393/// maps, so two runs over the same catalog are byte-identical.
394#[must_use]
395pub fn emit_oscal(entries: &[ControlMappingEntry]) -> EvidencePackage {
396    let metadata = || Metadata {
397        title: "CellOS 800-53 Rev5 candidate control mapping".to_string(),
398        version: "control-mapping-v1".to_string(),
399        remarks: PACKAGE_DISCLAIMER.to_string(),
400    };
401
402    let control_implementations = entries
403        .iter()
404        .map(|e| {
405            let mut props: BTreeMap<String, Vec<String>> = BTreeMap::new();
406            props.insert("codeSeams".to_string(), e.code_seams.clone());
407            props.insert(
408                "provingEventTypes".to_string(),
409                e.proving_event_types.clone(),
410            );
411            props.insert("provingTests".to_string(), e.proving_tests.clone());
412            ControlImplementation {
413                control_id: e.control_id.clone(),
414                status: e.status.clone(),
415                enforcement_binding: e.enforcement_binding.clone(),
416                description: e.narrative.clone(),
417                props,
418                remarks: remarks_for(e),
419            }
420        })
421        .collect();
422
423    let implemented_requirements = entries
424        .iter()
425        .map(|e| ImplementedRequirement {
426            control_id: e.control_id.clone(),
427            status: e.status.clone(),
428            description: e.narrative.clone(),
429            remarks: remarks_for(e),
430        })
431        .collect();
432
433    EvidencePackage {
434        component_definition: ComponentDefinition {
435            metadata: metadata(),
436            components: vec![Component {
437                uuid: "cellos-substrate-component-v1".to_string(),
438                component_type: "software".to_string(),
439                title: "CellOS execution-cell substrate".to_string(),
440                control_implementations,
441            }],
442        },
443        ssp_fragment: SspFragment {
444            metadata: metadata(),
445            implemented_requirements,
446        },
447    }
448}
449
450/// Serialize an [`EvidencePackage`] to deterministic pretty JSON bytes.
451///
452/// # Errors
453/// Returns the underlying `serde_json` error if serialization fails (it should
454/// not for these owned structs).
455pub fn emit_oscal_bytes(entries: &[ControlMappingEntry]) -> Result<Vec<u8>, serde_json::Error> {
456    let pkg = emit_oscal(entries);
457    let mut bytes = serde_json::to_vec_pretty(&pkg)?;
458    bytes.push(b'\n');
459    Ok(bytes)
460}