cleanlib_client/envelope.rs
1//! `VerdictEnvelopeV1` + `ReasonCode` — schema-locked mirror of
2//! `@cleanstart/cleanlib-sdk@0.4.1` (tarball sha-1
3//! `b5f00c160907a6ea1f490f14a9bda6f6de34b8b6`).
4//!
5//! Sister of:
6//! - sdk-js `dist/reason-codes.js` + `dist/verdict-envelope.schema.json`
7//! - sdk-py `cleanlib_sdk/reason_codes.py`
8//! - sdk-go `reason_codes.go`
9//!
10//! Drift between any of the four SDK consumers is a CI failure;
11//! `cleanlib-contract-fixtures` v1.0.0 verifies byte-identical
12//! `(status, reason_code)` across all 4 implementations.
13//!
14//! Freshness-precedence rule (ratified 2026-05-28; binding via App dispatch §4
15//! + Client dispatch §2.3): when the substance-driving signal's
16//! `availability == "degraded_stale"`, the substance-derived status tier is
17//! PRESERVED and the `reason_code` OVERRIDES to `VERDICT_DEGRADED_STALE`.
18//! Server-side `VERDICT_DEGRADED_STALE` is architecturally distinct from the
19//! client-side `LIVE_DEGRADED` cache-fallback state (extension status bar +
20//! Cli7 offline mode).
21
22use serde::{Deserialize, Serialize};
23
24/// Tri-state envelope status tier — sister of sdk-js Literal type
25/// `'ALLOW' | 'WARN' | 'DENY'`.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
27pub enum Status {
28 #[serde(rename = "ALLOW")]
29 Allow,
30 #[serde(rename = "WARN")]
31 Warn,
32 #[serde(rename = "DENY")]
33 Deny,
34}
35
36impl Status {
37 /// Canonical wire-format string — what App emits + what every other SDK
38 /// asserts on.
39 pub fn as_str(&self) -> &'static str {
40 match self {
41 Status::Allow => "ALLOW",
42 Status::Warn => "WARN",
43 Status::Deny => "DENY",
44 }
45 }
46}
47
48impl std::fmt::Display for Status {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 f.write_str(self.as_str())
51 }
52}
53
54/// Canonical 15-value `ReasonCode` registry — Rust mirror of sdk-js v0.4.1
55/// `dist/reason-codes.js`. Drift = CI failure.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
57pub enum ReasonCode {
58 // ─── Status outcomes (verdict-tier reasons) ──────────────────────────
59 #[serde(rename = "VERDICT_CLEAN")]
60 VerdictClean,
61 #[serde(rename = "VERDICT_RECOMMENDED_VERSION_NEWER")]
62 VerdictRecommendedVersionNewer,
63 #[serde(rename = "VERDICT_ABANDONED")]
64 VerdictAbandoned,
65 #[serde(rename = "VERDICT_LOW_TRUST")]
66 VerdictLowTrust,
67 /// CLEANLIB-511 (B2) / 503: unified reason for a VECTOR_VERDICT CVE finding
68 /// at LOW/MEDIUM/HIGH severity — retires the incoherent per-severity codes
69 /// (VERDICT_CLEAN on LOW = "no findings", VERDICT_ABANDONED on MEDIUM =
70 /// "unmaintained", VERDICT_LOW_TRUST on HIGH) which asserted facts unrelated
71 /// to "has a CVE". Severity is carried in `rich_data.severity`.
72 /// VERDICT_ABANDONED stays reserved for the genuine `abandonment_score`
73 /// signal (derive_status), VERDICT_EXPLOITATION_CRITICAL for CRITICAL.
74 #[serde(rename = "VERDICT_CVE_FOUND")]
75 VerdictCveFound,
76 /// CLEANLIB S1 (cycle-22, closes PM 731999 §1): canonical reason for a
77 /// not-yet-assessed package. `INSUFFICIENT_DATA` fails closed to WARN +
78 /// `VERDICT_NOT_YET_ASSESSED` — replaces the cycle-21 D1 `VERDICT_CLEAN`
79 /// placeholder (status-correct but reason-incoherent, Discipline #60).
80 #[serde(rename = "VERDICT_NOT_YET_ASSESSED")]
81 VerdictNotYetAssessed,
82 /// Server-side substrate freshness — substance-derived tier preserved,
83 /// reason overridden to surface staleness. Distinct from client-side
84 /// `LIVE_DEGRADED` cache-fallback (extension status bar; Cli7 offline mode).
85 #[serde(rename = "VERDICT_DEGRADED_STALE")]
86 VerdictDegradedStale,
87 #[serde(rename = "VERDICT_HAS_REMEDIATION")]
88 VerdictHasRemediation,
89 #[serde(rename = "VERDICT_KEV_LISTED")]
90 VerdictKevListed,
91 /// CLEANLIB-176: package named in ransomware campaigns
92 /// (`CVE_FINDING_ON_RANSOMWARE` source projection). Semantically distinct
93 /// from KEV — a CVE can be ransomware-linked without being CISA-KEV-listed
94 /// and vice-versa; conflating them defeats the 176 differentiation goal.
95 /// Cross-SDK + Threat ratification PENDING (see CLEANLIB-176 comment 658233).
96 #[serde(rename = "VERDICT_RANSOMWARE_LISTED")]
97 VerdictRansomwareListed,
98 #[serde(rename = "VERDICT_EXPLOITATION_CRITICAL")]
99 VerdictExploitationCritical,
100 /// CLEANLIB-176: confirmed/likely-malicious package (`MALICIOUS_TRIAGE`
101 /// source projection — typosquat / backdoor / protestware). Distinct from
102 /// `VERDICT_EXPLOITATION_CRITICAL` (a *CVE* being actively exploited):
103 /// malicious means remove + audit + rotate, not upgrade.
104 /// Cross-SDK + Threat ratification PENDING (see CLEANLIB-176 comment 658233).
105 #[serde(rename = "VERDICT_MALICIOUS")]
106 VerdictMalicious,
107 #[serde(rename = "VERDICT_OBFUSCATED")]
108 VerdictObfuscated,
109 #[serde(rename = "VERDICT_DENY_LIST")]
110 VerdictDenyList,
111
112 // ─── Client-transport reasons ────────────────────────────────────────
113 #[serde(rename = "CLIENT_NETWORK_UNREACHABLE")]
114 ClientNetworkUnreachable,
115 #[serde(rename = "CLIENT_AUTH_FAILED")]
116 ClientAuthFailed,
117 #[serde(rename = "CLIENT_BEARER_MISSING")]
118 ClientBearerMissing,
119 #[serde(rename = "CLIENT_RATE_LIMITED")]
120 ClientRateLimited,
121
122 // ─── Domain — 404 from /api/v1/remediation/:eco/:name ───────────────
123 #[serde(rename = "REMEDIATION_NOT_FOUND")]
124 RemediationNotFound,
125}
126
127impl ReasonCode {
128 /// Canonical wire-format string — what App emits + what every other SDK
129 /// asserts on.
130 pub fn as_str(&self) -> &'static str {
131 match self {
132 ReasonCode::VerdictClean => "VERDICT_CLEAN",
133 ReasonCode::VerdictRecommendedVersionNewer => "VERDICT_RECOMMENDED_VERSION_NEWER",
134 ReasonCode::VerdictAbandoned => "VERDICT_ABANDONED",
135 ReasonCode::VerdictLowTrust => "VERDICT_LOW_TRUST",
136 ReasonCode::VerdictCveFound => "VERDICT_CVE_FOUND",
137 ReasonCode::VerdictNotYetAssessed => "VERDICT_NOT_YET_ASSESSED",
138 ReasonCode::VerdictDegradedStale => "VERDICT_DEGRADED_STALE",
139 ReasonCode::VerdictHasRemediation => "VERDICT_HAS_REMEDIATION",
140 ReasonCode::VerdictKevListed => "VERDICT_KEV_LISTED",
141 ReasonCode::VerdictRansomwareListed => "VERDICT_RANSOMWARE_LISTED",
142 ReasonCode::VerdictExploitationCritical => "VERDICT_EXPLOITATION_CRITICAL",
143 ReasonCode::VerdictMalicious => "VERDICT_MALICIOUS",
144 ReasonCode::VerdictObfuscated => "VERDICT_OBFUSCATED",
145 ReasonCode::VerdictDenyList => "VERDICT_DENY_LIST",
146 ReasonCode::ClientNetworkUnreachable => "CLIENT_NETWORK_UNREACHABLE",
147 ReasonCode::ClientAuthFailed => "CLIENT_AUTH_FAILED",
148 ReasonCode::ClientBearerMissing => "CLIENT_BEARER_MISSING",
149 ReasonCode::ClientRateLimited => "CLIENT_RATE_LIMITED",
150 ReasonCode::RemediationNotFound => "REMEDIATION_NOT_FOUND",
151 }
152 }
153}
154
155impl std::fmt::Display for ReasonCode {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 f.write_str(self.as_str())
158 }
159}
160
161/// All 19 canonical reason-code values — consumed by drift-check CI.
162/// CLEANLIB-176 added `VERDICT_RANSOMWARE_LISTED` + `VERDICT_MALICIOUS` (15→17);
163/// S1 (cycle-22) added VERDICT_NOT_YET_ASSESSED (17→18); CLEANLIB-511(B2)/503 added VERDICT_CVE_FOUND (18→19). The
164/// three external SDKs (js/py/go) land these in coordinated follow-on PRs.
165pub const ALL_REASON_CODES: &[ReasonCode] = &[
166 ReasonCode::VerdictClean,
167 ReasonCode::VerdictRecommendedVersionNewer,
168 ReasonCode::VerdictAbandoned,
169 ReasonCode::VerdictLowTrust,
170 ReasonCode::VerdictCveFound,
171 ReasonCode::VerdictNotYetAssessed,
172 ReasonCode::VerdictDegradedStale,
173 ReasonCode::VerdictHasRemediation,
174 ReasonCode::VerdictKevListed,
175 ReasonCode::VerdictRansomwareListed,
176 ReasonCode::VerdictExploitationCritical,
177 ReasonCode::VerdictMalicious,
178 ReasonCode::VerdictObfuscated,
179 ReasonCode::VerdictDenyList,
180 ReasonCode::ClientNetworkUnreachable,
181 ReasonCode::ClientAuthFailed,
182 ReasonCode::ClientBearerMissing,
183 ReasonCode::ClientRateLimited,
184 ReasonCode::RemediationNotFound,
185];
186
187/// Canonical wire-strings for the verdict `source` field — Rust mirror of
188/// `cleanlib_core::VerdictSource` SCREAMING_SNAKE serde output. The first four
189/// are the cycle-≤16 originals; the last four are the CLEANLIB-176 projection
190/// variants that let customers separate "has CVEs" (upgrade) from "actively
191/// exploited" (KEV) / "ransomware-linked" / "malicious" (remove+audit+rotate).
192/// Used by [`crate::verdict_to_envelope_v1`] to refine the reason_code by
193/// source while preserving the label-derived status tier.
194pub const ALL_VERDICT_SOURCES: &[&str] = &[
195 "ALLOWED_NO_FINDINGS",
196 "VECTOR_VERDICT",
197 "DM_THRESHOLD_BLOCK",
198 "INSUFFICIENT_DATA",
199 "CVE_FINDING",
200 "CVE_FINDING_ON_KEV",
201 "CVE_FINDING_ON_RANSOMWARE",
202 "MALICIOUS_TRIAGE",
203];
204
205/// `VerdictEnvelopeV1` — parsed shape of the `verdict-envelope.v1.json`
206/// schema. Top-level fields are required; rich sub-objects are sparse and
207/// `#[serde(default)]`-tolerant so the SDK can consume partial responses
208/// during cycle-N spec evolution without forcing a recompile.
209///
210/// Sister of:
211/// - sdk-js `VerdictEnvelopeV1Schema` (zod)
212/// - sdk-py no struct (dict[str, Any] in Python)
213/// - sdk-go `map[string]any` (loose) — but Rust gets a typed struct.
214#[derive(Debug, Clone, Deserialize, Serialize)]
215pub struct VerdictEnvelopeV1 {
216 pub status: String,
217 pub reason_code: String,
218 pub human_message: String,
219 pub as_of: String,
220 /// CLEANLIB-505 (III): full-nanosecond `as_of`, dual-emitted alongside the
221 /// (possibly µs-truncated) `as_of` string. Additive migration-window field
222 /// (A3-style) — Python truncates `as_of` to µs at datetime-parse, so the
223 /// raw ns timestamp is carried here as a string for consumers that need
224 /// sub-µs precision. Rust preserves ns in `as_of` already, so this mirrors
225 /// it. `skip_serializing_if = None` → byte-identical v1 when absent.
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub as_of_ns: Option<String>,
228
229 #[serde(default)]
230 pub rich_data: Option<serde_json::Value>,
231 #[serde(default)]
232 pub remediation: Option<serde_json::Value>,
233 #[serde(default)]
234 pub exploitability: Option<serde_json::Value>,
235 /// CLEANLIB-104 App-3.1 Gate M3: non-Optional per the design doc §3.3
236 /// exit criterion ("derive_status.rs line 57 stops using as_ref on
237 /// availability"). `#[serde(default)]` gives `Value::Null` on absent-key
238 /// payloads — fail-open: consumers see a defaulted block, not an
239 /// unwrap-panic. `derive_status.rs` uses `Some(&envelope.availability)`
240 /// against the untyped JSON-Value helpers (see line 57).
241 ///
242 /// `skip_serializing_if = "Value::is_null"` preserves the wire byte-
243 /// identity on happy-path envelopes: when the adapter passes through a
244 /// default `AvailabilityBlock` (degraded_stale=false), the envelope
245 /// serializes as `Null` and the field is omitted — matching the pre-M3
246 /// `Option<Value>::None` shape.
247 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
248 pub availability: serde_json::Value,
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
256 fn parses_minimal_envelope() {
257 let json = r#"{
258 "status": "ALLOW",
259 "reason_code": "VERDICT_CLEAN",
260 "human_message": "ok",
261 "as_of": "2026-05-28"
262 }"#;
263 let env: VerdictEnvelopeV1 = serde_json::from_str(json).unwrap();
264 assert_eq!(env.status, "ALLOW");
265 assert_eq!(env.reason_code, "VERDICT_CLEAN");
266 assert!(env.rich_data.is_none());
267 assert!(env.remediation.is_none());
268 assert!(env.exploitability.is_none());
269 // CLEANLIB-104 M3: availability is non-Optional; absent JSON key
270 // deserializes to `Value::Null` (the serde default for
271 // `serde_json::Value`).
272 assert!(env.availability.is_null());
273 }
274
275 #[test]
276 fn all_19_reason_codes_present() {
277 // Drift-check sister of sdk-py ALL_REASON_CODES + sdk-go AllReasonCodes.
278 // CLEANLIB-176: 15 → 17 (+VERDICT_RANSOMWARE_LISTED +VERDICT_MALICIOUS).
279 // S1 (cycle-22, PM 731999 §1): 17 → 18 (+VERDICT_NOT_YET_ASSESSED).
280 assert_eq!(ALL_REASON_CODES.len(), 19);
281 assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictCveFound));
282 assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictNotYetAssessed));
283 }
284
285 #[test]
286 fn all_verdict_sources_recognized() {
287 // CLEANLIB-176: the SDK must recognize all 8 wire-strings for the
288 // verdict `source` field (4 originals + 4 projection variants) so it
289 // never silently misclassifies a known source as unknown.
290 assert_eq!(ALL_VERDICT_SOURCES.len(), 8);
291 assert!(ALL_VERDICT_SOURCES.contains(&"CVE_FINDING_ON_KEV"));
292 assert!(ALL_VERDICT_SOURCES.contains(&"CVE_FINDING_ON_RANSOMWARE"));
293 assert!(ALL_VERDICT_SOURCES.contains(&"MALICIOUS_TRIAGE"));
294 }
295
296 #[test]
297 fn reason_code_string_roundtrip() {
298 for rc in ALL_REASON_CODES {
299 let s = serde_json::to_string(rc).unwrap();
300 let back: ReasonCode = serde_json::from_str(&s).unwrap();
301 assert_eq!(&back, rc);
302 // as_str() matches serde wire format (quoted JSON string).
303 assert_eq!(format!("\"{}\"", rc.as_str()), s);
304 }
305 }
306
307 #[test]
308 fn status_string_roundtrip() {
309 for st in [Status::Allow, Status::Warn, Status::Deny] {
310 let s = serde_json::to_string(&st).unwrap();
311 let back: Status = serde_json::from_str(&s).unwrap();
312 assert_eq!(back, st);
313 assert_eq!(format!("\"{}\"", st.as_str()), s);
314 }
315 }
316}