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 /// CLEANLIB-518 (§3): the App could not resolve the requested semver range
112 /// to a concrete version (`source_state = RANGE_NOT_RESOLVED`, CLEANLIB-513).
113 /// Distinct from `VERDICT_NOT_YET_ASSESSED` — the package is not un-assessed,
114 /// the *range* is unresolved, so the customer must pin a concrete version.
115 /// Fixes the CLI banner↔body contradiction where a range-not-resolved verdict
116 /// rendered the "❔ Not yet assessed" banner while the reasoning body said the
117 /// opposite. Fails CLOSED to WARN (an unresolved range is not an ALLOW).
118 #[serde(rename = "VERDICT_RANGE_NOT_RESOLVED")]
119 VerdictRangeNotResolved,
120
121 // ─── Client-transport reasons ────────────────────────────────────────
122 #[serde(rename = "CLIENT_NETWORK_UNREACHABLE")]
123 ClientNetworkUnreachable,
124 #[serde(rename = "CLIENT_AUTH_FAILED")]
125 ClientAuthFailed,
126 #[serde(rename = "CLIENT_BEARER_MISSING")]
127 ClientBearerMissing,
128 #[serde(rename = "CLIENT_RATE_LIMITED")]
129 ClientRateLimited,
130
131 // ─── Domain — 404 from /api/v1/remediation/:eco/:name ───────────────
132 #[serde(rename = "REMEDIATION_NOT_FOUND")]
133 RemediationNotFound,
134}
135
136impl ReasonCode {
137 /// Canonical wire-format string — what App emits + what every other SDK
138 /// asserts on.
139 pub fn as_str(&self) -> &'static str {
140 match self {
141 ReasonCode::VerdictClean => "VERDICT_CLEAN",
142 ReasonCode::VerdictRecommendedVersionNewer => "VERDICT_RECOMMENDED_VERSION_NEWER",
143 ReasonCode::VerdictAbandoned => "VERDICT_ABANDONED",
144 ReasonCode::VerdictLowTrust => "VERDICT_LOW_TRUST",
145 ReasonCode::VerdictCveFound => "VERDICT_CVE_FOUND",
146 ReasonCode::VerdictNotYetAssessed => "VERDICT_NOT_YET_ASSESSED",
147 ReasonCode::VerdictDegradedStale => "VERDICT_DEGRADED_STALE",
148 ReasonCode::VerdictHasRemediation => "VERDICT_HAS_REMEDIATION",
149 ReasonCode::VerdictKevListed => "VERDICT_KEV_LISTED",
150 ReasonCode::VerdictRansomwareListed => "VERDICT_RANSOMWARE_LISTED",
151 ReasonCode::VerdictExploitationCritical => "VERDICT_EXPLOITATION_CRITICAL",
152 ReasonCode::VerdictMalicious => "VERDICT_MALICIOUS",
153 ReasonCode::VerdictObfuscated => "VERDICT_OBFUSCATED",
154 ReasonCode::VerdictDenyList => "VERDICT_DENY_LIST",
155 ReasonCode::VerdictRangeNotResolved => "VERDICT_RANGE_NOT_RESOLVED",
156 ReasonCode::ClientNetworkUnreachable => "CLIENT_NETWORK_UNREACHABLE",
157 ReasonCode::ClientAuthFailed => "CLIENT_AUTH_FAILED",
158 ReasonCode::ClientBearerMissing => "CLIENT_BEARER_MISSING",
159 ReasonCode::ClientRateLimited => "CLIENT_RATE_LIMITED",
160 ReasonCode::RemediationNotFound => "REMEDIATION_NOT_FOUND",
161 }
162 }
163}
164
165impl std::fmt::Display for ReasonCode {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 f.write_str(self.as_str())
168 }
169}
170
171/// All 20 canonical reason-code values — consumed by drift-check CI.
172/// CLEANLIB-176 added `VERDICT_RANSOMWARE_LISTED` + `VERDICT_MALICIOUS` (15→17);
173/// S1 (cycle-22) added VERDICT_NOT_YET_ASSESSED (17→18); CLEANLIB-511(B2)/503 added VERDICT_CVE_FOUND (18→19);
174/// CLEANLIB-518(§3) added VERDICT_RANGE_NOT_RESOLVED (19→20). The
175/// three external SDKs (js/py/go) land these in coordinated follow-on PRs.
176pub const ALL_REASON_CODES: &[ReasonCode] = &[
177 ReasonCode::VerdictClean,
178 ReasonCode::VerdictRecommendedVersionNewer,
179 ReasonCode::VerdictAbandoned,
180 ReasonCode::VerdictLowTrust,
181 ReasonCode::VerdictCveFound,
182 ReasonCode::VerdictNotYetAssessed,
183 ReasonCode::VerdictDegradedStale,
184 ReasonCode::VerdictHasRemediation,
185 ReasonCode::VerdictKevListed,
186 ReasonCode::VerdictRansomwareListed,
187 ReasonCode::VerdictExploitationCritical,
188 ReasonCode::VerdictMalicious,
189 ReasonCode::VerdictObfuscated,
190 ReasonCode::VerdictDenyList,
191 ReasonCode::VerdictRangeNotResolved,
192 ReasonCode::ClientNetworkUnreachable,
193 ReasonCode::ClientAuthFailed,
194 ReasonCode::ClientBearerMissing,
195 ReasonCode::ClientRateLimited,
196 ReasonCode::RemediationNotFound,
197];
198
199/// Canonical wire-strings for the verdict `source` field — Rust mirror of
200/// `cleanlib_core::VerdictSource` SCREAMING_SNAKE serde output. The first four
201/// are the cycle-≤16 originals; the last four are the CLEANLIB-176 projection
202/// variants that let customers separate "has CVEs" (upgrade) from "actively
203/// exploited" (KEV) / "ransomware-linked" / "malicious" (remove+audit+rotate).
204/// Used by [`crate::verdict_to_envelope_v1`] to refine the reason_code by
205/// source while preserving the label-derived status tier.
206pub const ALL_VERDICT_SOURCES: &[&str] = &[
207 "ALLOWED_NO_FINDINGS",
208 "VECTOR_VERDICT",
209 "DM_THRESHOLD_BLOCK",
210 "INSUFFICIENT_DATA",
211 "CVE_FINDING",
212 "CVE_FINDING_ON_KEV",
213 "CVE_FINDING_ON_RANSOMWARE",
214 "MALICIOUS_TRIAGE",
215];
216
217/// `VerdictEnvelopeV1` — parsed shape of the `verdict-envelope.v1.json`
218/// schema. Top-level fields are required; rich sub-objects are sparse and
219/// `#[serde(default)]`-tolerant so the SDK can consume partial responses
220/// during cycle-N spec evolution without forcing a recompile.
221///
222/// Sister of:
223/// - sdk-js `VerdictEnvelopeV1Schema` (zod)
224/// - sdk-py no struct (dict[str, Any] in Python)
225/// - sdk-go `map[string]any` (loose) — but Rust gets a typed struct.
226#[derive(Debug, Clone, Deserialize, Serialize)]
227pub struct VerdictEnvelopeV1 {
228 pub status: String,
229 pub reason_code: String,
230 pub human_message: String,
231 pub as_of: String,
232 /// CLEANLIB-505 (III): full-nanosecond `as_of`, dual-emitted alongside the
233 /// (possibly µs-truncated) `as_of` string. Additive migration-window field
234 /// (A3-style) — Python truncates `as_of` to µs at datetime-parse, so the
235 /// raw ns timestamp is carried here as a string for consumers that need
236 /// sub-µs precision. Rust preserves ns in `as_of` already, so this mirrors
237 /// it. `skip_serializing_if = None` → byte-identical v1 when absent.
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub as_of_ns: Option<String>,
240
241 #[serde(default)]
242 pub rich_data: Option<serde_json::Value>,
243 #[serde(default)]
244 pub remediation: Option<serde_json::Value>,
245 #[serde(default)]
246 pub exploitability: Option<serde_json::Value>,
247 /// CLEANLIB-104 App-3.1 Gate M3: non-Optional per the design doc §3.3
248 /// exit criterion ("derive_status.rs line 57 stops using as_ref on
249 /// availability"). `#[serde(default)]` gives `Value::Null` on absent-key
250 /// payloads — fail-open: consumers see a defaulted block, not an
251 /// unwrap-panic. `derive_status.rs` uses `Some(&envelope.availability)`
252 /// against the untyped JSON-Value helpers (see line 57).
253 ///
254 /// `skip_serializing_if = "Value::is_null"` preserves the wire byte-
255 /// identity on happy-path envelopes: when the adapter passes through a
256 /// default `AvailabilityBlock` (degraded_stale=false), the envelope
257 /// serializes as `Null` and the field is omitted — matching the pre-M3
258 /// `Option<Value>::None` shape.
259 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
260 pub availability: serde_json::Value,
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn parses_minimal_envelope() {
269 let json = r#"{
270 "status": "ALLOW",
271 "reason_code": "VERDICT_CLEAN",
272 "human_message": "ok",
273 "as_of": "2026-05-28"
274 }"#;
275 let env: VerdictEnvelopeV1 = serde_json::from_str(json).unwrap();
276 assert_eq!(env.status, "ALLOW");
277 assert_eq!(env.reason_code, "VERDICT_CLEAN");
278 assert!(env.rich_data.is_none());
279 assert!(env.remediation.is_none());
280 assert!(env.exploitability.is_none());
281 // CLEANLIB-104 M3: availability is non-Optional; absent JSON key
282 // deserializes to `Value::Null` (the serde default for
283 // `serde_json::Value`).
284 assert!(env.availability.is_null());
285 }
286
287 #[test]
288 fn all_20_reason_codes_present() {
289 // Drift-check sister of sdk-py ALL_REASON_CODES + sdk-go AllReasonCodes.
290 // CLEANLIB-176: 15 → 17 (+VERDICT_RANSOMWARE_LISTED +VERDICT_MALICIOUS).
291 // S1 (cycle-22, PM 731999 §1): 17 → 18 (+VERDICT_NOT_YET_ASSESSED).
292 // CLEANLIB-511(B2)/503: 18 → 19 (+VERDICT_CVE_FOUND).
293 // CLEANLIB-518(§3): 19 → 20 (+VERDICT_RANGE_NOT_RESOLVED).
294 assert_eq!(ALL_REASON_CODES.len(), 20);
295 assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictCveFound));
296 assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictNotYetAssessed));
297 assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictRangeNotResolved));
298 }
299
300 #[test]
301 fn all_verdict_sources_recognized() {
302 // CLEANLIB-176: the SDK must recognize all 8 wire-strings for the
303 // verdict `source` field (4 originals + 4 projection variants) so it
304 // never silently misclassifies a known source as unknown.
305 assert_eq!(ALL_VERDICT_SOURCES.len(), 8);
306 assert!(ALL_VERDICT_SOURCES.contains(&"CVE_FINDING_ON_KEV"));
307 assert!(ALL_VERDICT_SOURCES.contains(&"CVE_FINDING_ON_RANSOMWARE"));
308 assert!(ALL_VERDICT_SOURCES.contains(&"MALICIOUS_TRIAGE"));
309 }
310
311 #[test]
312 fn reason_code_string_roundtrip() {
313 for rc in ALL_REASON_CODES {
314 let s = serde_json::to_string(rc).unwrap();
315 let back: ReasonCode = serde_json::from_str(&s).unwrap();
316 assert_eq!(&back, rc);
317 // as_str() matches serde wire format (quoted JSON string).
318 assert_eq!(format!("\"{}\"", rc.as_str()), s);
319 }
320 }
321
322 #[test]
323 fn status_string_roundtrip() {
324 for st in [Status::Allow, Status::Warn, Status::Deny] {
325 let s = serde_json::to_string(&st).unwrap();
326 let back: Status = serde_json::from_str(&s).unwrap();
327 assert_eq!(back, st);
328 assert_eq!(format!("\"{}\"", st.as_str()), s);
329 }
330 }
331}