tatara_process/compliance.rs
1//! Compliance bindings — CRD-facing with bridges to `tatara_core::compliance_binding`.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6use tatara_core::domain::compliance_binding as core;
7
8use crate::phase::ProcessPhase;
9
10/// Compliance section of `ProcessSpec`.
11#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
12#[serde(rename_all = "camelCase")]
13pub struct ComplianceSpec {
14 /// Canonical baseline (e.g., `fedramp-moderate`, `cis-k8s-v1.8`, `soc2`, `pci-dss`).
15 /// Semantically the `meet` of all `bindings`.
16 #[serde(default, skip_serializing_if = "Option::is_none")]
17 pub baseline: Option<String>,
18 /// Individual control bindings.
19 #[serde(default)]
20 pub bindings: Vec<ComplianceBinding>,
21 /// Allow the reconciler to invoke remediation hooks on violations.
22 #[serde(default)]
23 pub auto_remediate: bool,
24}
25
26#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
27#[serde(rename_all = "camelCase")]
28pub struct ComplianceBinding {
29 /// Framework name: `nist-800-53`, `cis-k8s-v1.8`, `fedramp-moderate`, `soc2`, `pci-dss`.
30 pub framework: String,
31 /// Control id within the framework (e.g., `SC-7`, `5.1.1`).
32 pub control_id: String,
33 /// When the binding is verified.
34 #[serde(default)]
35 pub phase: VerificationPhase,
36 /// Optional human description.
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub description: Option<String>,
39}
40
41/// When a ComplianceBinding is evaluated.
42#[derive(
43 Clone,
44 Copy,
45 Debug,
46 PartialEq,
47 Eq,
48 Hash,
49 Serialize,
50 Deserialize,
51 JsonSchema,
52 Default,
53 tatara_closed_set::DeriveClosedSet,
54)]
55#[serde(rename_all = "PascalCase")]
56#[closed_set(via = "as_str", generate_unknown, display)]
57pub enum VerificationPhase {
58 /// Before Execing — fails reconciliation if violated.
59 PlanTime,
60 /// During VERIFY — gates Running → Attested.
61 #[default]
62 AtBoundary,
63 /// After Attested — continuous audit, emits events on violation.
64 PostConvergence,
65}
66
67impl VerificationPhase {
68 /// The closed set of verification phases — single source of truth that
69 /// drives the `as_str` / Display / `FromStr` triad and the typed
70 /// `gates_phase` projection over [`ProcessPhase`]. Adding a fourth
71 /// variant lands at one `ALL` entry + one `as_str` arm + one
72 /// `gates_phase` arm — exhaustively checked by the compiler (the
73 /// `[Self; 3]` array literal forces the arity).
74 ///
75 /// Sibling closed-set lifts on the same `ProcessSpec` axis:
76 /// [`crate::signal::SighupStrategy::ALL`],
77 /// [`crate::spec::MustReachPhase::ALL`],
78 /// [`crate::intent::WorkloadKind::ALL`],
79 /// [`crate::export::ReportFormat::ALL`],
80 /// [`crate::encapsulates::EncapsulationMode::ALL`],
81 /// [`crate::export::ExportTrigger::ALL`],
82 /// [`crate::lifetime::TeardownPolicy::ALL`],
83 /// [`crate::boundary::ConditionKind::ALL`],
84 /// [`crate::lifetime::LifetimeKind::ALL`],
85 /// [`crate::intent::IntentKind::ALL`],
86 /// [`crate::phase::ProcessPhase::ALL`],
87 /// [`crate::signal::ProcessSignal::ALL`].
88 pub const ALL: [Self; 3] = [Self::PlanTime, Self::AtBoundary, Self::PostConvergence];
89
90 /// Canonical PascalCase wire-format projection — matches the serde
91 /// `rename_all = "PascalCase"` output verbatim AND the CRD `enum:`
92 /// enumeration the reconciler stamps on the
93 /// `processes.tatara.pleme.io` schema. Pinned by
94 /// `verification_phase_as_str_matches_serde` so a variant rename
95 /// can't drift between the typed surface, the CRD enum, and the
96 /// YAML wire format at one site.
97 pub const fn as_str(self) -> &'static str {
98 match self {
99 Self::PlanTime => "PlanTime",
100 Self::AtBoundary => "AtBoundary",
101 Self::PostConvergence => "PostConvergence",
102 }
103 }
104
105 /// Typed `const fn` projection onto the [`ProcessPhase`] gate the
106 /// binding's verification blocks when it fails. Each variant maps
107 /// to the earliest phase whose entry the binding can prevent:
108 ///
109 /// - `PlanTime` → `Some(Execing)` — the RENDER phase is what
110 /// PlanTime gates ("Before Execing — fails reconciliation if
111 /// violated"); a violated PlanTime control prevents the
112 /// `Forking → Execing` transition.
113 /// - `AtBoundary` → `Some(Attested)` — the VERIFY phase ("gates
114 /// Running → Attested"); a violated AtBoundary control prevents
115 /// the `Running → Attested` transition.
116 /// - `PostConvergence` → `None` — the binding is non-blocking
117 /// ("After Attested — continuous audit, emits events on
118 /// violation"); it never gates a transition.
119 ///
120 /// Single source of truth for the future reconciler control-plane
121 /// compliance evaluator's "which transition would a failing
122 /// binding block?" decision; pinned by
123 /// `verification_phase_gates_phase_truth_table`. Closed-set match
124 /// (not `matches!`) so adding a fourth variant triggers the
125 /// compiler's exhaustiveness check at this site rather than
126 /// silently defaulting to either group.
127 pub const fn gates_phase(self) -> Option<ProcessPhase> {
128 match self {
129 Self::PlanTime => Some(ProcessPhase::Execing),
130 Self::AtBoundary => Some(ProcessPhase::Attested),
131 Self::PostConvergence => None,
132 }
133 }
134}
135
136// `impl FromStr for VerificationPhase` +
137// `impl tatara_lisp::ClosedSet for VerificationPhase` +
138// `impl fmt::Display for VerificationPhase` +
139// `pub struct UnknownVerificationPhase(pub String)` are all
140// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` +
141// `#[closed_set(via = "as_str", generate_unknown, display)]` on the
142// enum declaration above. `label` delegates to the inherent
143// `VerificationPhase::as_str` (which matches the serde
144// `rename_all = "PascalCase"` projection AND the CRD `enum:`
145// enumeration verbatim — pinned by
146// `verification_phase_as_str_matches_serde`). The auto-derived
147// carrier label "verification phase" matches the prior hand-rolled
148// `#[error("unknown verification phase: {0}")]` annotation
149// byte-for-byte. Symmetric to every other `#[derive(DeriveClosedSet)]`
150// implementor across the crate.
151
152impl From<VerificationPhase> for core::VerificationPhase {
153 fn from(v: VerificationPhase) -> Self {
154 match v {
155 VerificationPhase::PlanTime => Self::PlanTime,
156 VerificationPhase::AtBoundary => Self::AtBoundary,
157 VerificationPhase::PostConvergence => Self::PostConvergence,
158 }
159 }
160}
161
162impl From<core::VerificationPhase> for VerificationPhase {
163 fn from(v: core::VerificationPhase) -> Self {
164 use core::VerificationPhase as C;
165 match v {
166 C::PlanTime => Self::PlanTime,
167 C::AtBoundary => Self::AtBoundary,
168 C::PostConvergence => Self::PostConvergence,
169 }
170 }
171}
172
173impl ComplianceBinding {
174 pub fn to_core(&self) -> core::ComplianceControl {
175 core::ComplianceControl {
176 framework: self.framework.clone(),
177 control_id: self.control_id.clone(),
178 description: self.description.clone().unwrap_or_default(),
179 }
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn default_phase_is_at_boundary() {
189 assert_eq!(VerificationPhase::default(), VerificationPhase::AtBoundary);
190 }
191
192 #[test]
193 fn binding_roundtrip_to_core() {
194 let b = ComplianceBinding {
195 framework: "nist-800-53".into(),
196 control_id: "SC-7".into(),
197 phase: VerificationPhase::AtBoundary,
198 description: Some("boundary protection".into()),
199 };
200 let c = b.to_core();
201 assert_eq!(c.framework, "nist-800-53");
202 assert_eq!(c.control_id, "SC-7");
203 }
204
205 // ── closed-set algebra contracts (ALL × as_str × FromStr × gates_phase) ──
206
207 /// Structural well-formedness of [`VerificationPhase`] as a
208 /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
209 /// testkit lift that pins all three structural invariants
210 /// (`ALL` is non-empty, every variant round-trips through
211 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
212 /// outside the closed set) at ONE call site. Replaces the
213 /// hand-derived `verification_phase_all_is_unique_and_complete` +
214 /// `verification_phase_roundtrip_via_as_str` + the empty-input
215 /// arm of the per-implementor unknown-error test. `FromStr`
216 /// delegates to `<Self as tatara_closed_set::ClosedSet>::parse_label`,
217 /// so this helper exercises the same code path the reconciler
218 /// hits when parsing a CRD `enum:`-validated value back to the
219 /// typed phase.
220 #[test]
221 fn verification_phase_is_well_formed_closed_set() {
222 tatara_closed_set::assert_closed_set_well_formed::<VerificationPhase>();
223 }
224
225 /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
226 /// output verbatim for every variant. A future variant rename
227 /// (or an `as_str` arm typo) lands here at one site, instead of
228 /// drifting between the typed surface and the YAML wire format
229 /// the reconciler / operator both read. NOT lifted into the
230 /// `ClosedSet` testkit — `serde_json` is NOT a `tatara-lisp`
231 /// dependency, and per-implementor serde-shape choices (PascalCase
232 /// for CRD enums, snake_case for camelCase carriers, lowercase
233 /// for Lisp keyword projections) make a generic helper a
234 /// category error.
235 #[test]
236 fn verification_phase_as_str_matches_serde() {
237 for phase in VerificationPhase::ALL {
238 let serialized = serde_json::to_string(&phase).expect("serialize");
239 let unquoted = serialized
240 .trim_start_matches('"')
241 .trim_end_matches('"')
242 .to_string();
243 assert_eq!(
244 unquoted,
245 phase.as_str(),
246 "as_str drift for {phase:?}: as_str={} serde={unquoted}",
247 phase.as_str()
248 );
249 }
250 }
251
252 /// The Display impl IS `as_str` — pinning this lets future callers
253 /// reach for either projection without drift.
254 #[test]
255 fn verification_phase_display_matches_as_str() {
256 for phase in VerificationPhase::ALL {
257 assert_eq!(phase.to_string(), phase.as_str());
258 }
259 }
260
261 /// `FromStr` rejects domain-specific non-canonical inputs and
262 /// the error echoes the input VERBATIM so the operator-facing
263 /// diagnostic carries the offending value. Kept per-implementor
264 /// because the verbatim-payload contract is a property of the
265 /// per-enum `Unknown<X>(pub String)` newtype, not of the trait's
266 /// structural surface. (The empty-input arm is now lifted into
267 /// `verification_phase_is_well_formed_closed_set`; the
268 /// case-drifted / hyphenated / extinct-variant arms stay here as
269 /// they're representative non-canonical inputs the operator
270 /// might supply.)
271 #[test]
272 fn unknown_verification_phase_errors() {
273 use std::str::FromStr;
274 for bad in [
275 "plantime",
276 "ATBOUNDARY",
277 "Plan-Time",
278 "post_convergence",
279 "Continuous",
280 ] {
281 let err = VerificationPhase::from_str(bad).unwrap_err();
282 assert_eq!(err.0, bad, "error payload should echo input verbatim");
283 }
284 }
285
286 /// TRUTH-TABLE CONTRACT: `gates_phase` agrees with the documented
287 /// per-variant codomain (the phase whose entry a violated binding
288 /// blocks, or `None` for non-blocking continuous-audit phases).
289 #[test]
290 fn verification_phase_gates_phase_truth_table() {
291 assert_eq!(
292 VerificationPhase::PlanTime.gates_phase(),
293 Some(ProcessPhase::Execing)
294 );
295 assert_eq!(
296 VerificationPhase::AtBoundary.gates_phase(),
297 Some(ProcessPhase::Attested)
298 );
299 assert_eq!(VerificationPhase::PostConvergence.gates_phase(), None);
300 }
301
302 /// SUBSET CONTRACT: every `Some(target)` `gates_phase` projects to
303 /// is a phase reachable as the destination of some legal
304 /// `ProcessPhase::can_transition_to` edge. A future variant that
305 /// projected to a `ProcessPhase` no transition leads into would
306 /// FAIL here, forcing the author to either pick a real gate phase
307 /// or extend `can_transition_to` deliberately. The reachability
308 /// check is the cross-enum coherence proof — the typed-phase
309 /// state machine and the verification-phase gate algebra agree on
310 /// which phases are gateable.
311 #[test]
312 fn verification_phase_gates_phase_projects_to_reachable_phases() {
313 for vp in VerificationPhase::ALL {
314 if let Some(target) = vp.gates_phase() {
315 let reachable = ProcessPhase::ALL
316 .into_iter()
317 .any(|src| src != target && src.can_transition_to(target));
318 assert!(
319 reachable,
320 "{vp:?}.gates_phase() = Some({target:?}) but no legal transition lands on {target:?}",
321 );
322 }
323 }
324 }
325
326 /// INJECTIVITY CONTRACT: distinct `Some` variants of `gates_phase`
327 /// project to distinct `ProcessPhase`s. Pairing this with the
328 /// subset contract above forces a future variant to land on a
329 /// fresh gateable phase (or project to `None` and be a deliberate
330 /// non-blocking auditor).
331 #[test]
332 fn verification_phase_gates_phase_is_injective() {
333 let projections: Vec<ProcessPhase> = VerificationPhase::ALL
334 .into_iter()
335 .filter_map(VerificationPhase::gates_phase)
336 .collect();
337 let unique: std::collections::HashSet<_> = projections.iter().copied().collect();
338 assert_eq!(
339 projections.len(),
340 unique.len(),
341 "gates_phase projection is not injective: {projections:?}",
342 );
343 }
344}