1use 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
48pub const CATALOG_RELPATH: &str = "contracts/controls/cellos-800-53-rev5-mapping.json";
50
51pub const SCHEMA_RELPATH: &str = "contracts/schemas/control-mapping-v1.schema.json";
53
54pub const CANDIDATE_REMARK: &str = "candidate, not assessor-verified";
56
57pub const CRYPTO_NOT_VALIDATED_REMARK: &str = "crypto module NOT CMVP-validated";
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct ControlMappingEntry {
66 pub control_id: String,
68 pub status: String,
70 #[serde(default = "default_binding")]
72 pub enforcement_binding: String,
73 #[serde(default)]
75 pub code_seams: Vec<String>,
76 #[serde(default)]
78 pub proving_event_types: Vec<String>,
79 #[serde(default)]
81 pub proving_tests: Vec<String>,
82 pub narrative: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub degraded_binding_note: Option<String>,
88 #[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 #[must_use]
100 pub fn is_implemented(&self) -> bool {
101 self.status == "implemented"
102 }
103
104 #[must_use]
106 pub fn is_nftables_bound(&self) -> bool {
107 self.enforcement_binding == "linux-nftables"
108 }
109
110 #[must_use]
112 pub fn is_algorithm_present_not_validated(&self) -> bool {
113 self.status == "algorithm-present-not-validated"
114 }
115}
116
117#[derive(Debug, thiserror::Error)]
119pub enum EvidenceError {
120 #[error("io error reading {path}: {source}")]
122 Io {
123 path: String,
125 source: std::io::Error,
127 },
128 #[error("catalog parse error: {0}")]
130 Parse(#[from] serde_json::Error),
131 #[error("catalog lint failed with {} finding(s):\n - {}", .0.len(), .0.join("\n - "))]
133 Lint(Vec<String>),
134 #[error("schema error: {0}")]
136 Schema(#[from] SchemaError),
137}
138
139#[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
150pub 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
165pub 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
181pub 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275pub struct EvidencePackage {
276 #[serde(rename = "component-definition")]
278 pub component_definition: ComponentDefinition,
279 #[serde(rename = "ssp-fragment")]
281 pub ssp_fragment: SspFragment,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286pub struct ComponentDefinition {
287 pub metadata: Metadata,
289 pub components: Vec<Component>,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295pub struct SspFragment {
296 pub metadata: Metadata,
298 #[serde(rename = "implemented-requirements")]
300 pub implemented_requirements: Vec<ImplementedRequirement>,
301}
302
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305pub struct Metadata {
306 pub title: String,
308 pub version: String,
310 pub remarks: String,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct Component {
317 pub uuid: String,
319 #[serde(rename = "type")]
321 pub component_type: String,
322 pub title: String,
324 #[serde(rename = "control-implementations")]
326 pub control_implementations: Vec<ControlImplementation>,
327}
328
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331pub struct ControlImplementation {
332 #[serde(rename = "control-id")]
334 pub control_id: String,
335 pub status: String,
337 #[serde(rename = "enforcement-binding")]
339 pub enforcement_binding: String,
340 pub description: String,
342 pub props: BTreeMap<String, Vec<String>>,
344 pub remarks: Vec<String>,
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350pub struct ImplementedRequirement {
351 #[serde(rename = "control-id")]
353 pub control_id: String,
354 pub status: String,
356 pub description: String,
358 pub remarks: Vec<String>,
360}
361
362const 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
368fn remarks_for(entry: &ControlMappingEntry) -> Vec<String> {
373 let mut remarks = Vec::new();
374 remarks.push(CANDIDATE_REMARK.to_string());
376 if entry.is_algorithm_present_not_validated() {
378 remarks.push(CRYPTO_NOT_VALIDATED_REMARK.to_string());
379 }
380 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#[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
450pub 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}