cleanlib-client 0.1.8

HTTP client SDK for the CleanLibrary verdict API — VerdictEnvelopeV1 types, derive_status logic, transport, config, and risk-acceptance YAML emitter shared between cleanlib-cli and other CleanLibrary consumers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! CLEANLIB-178 — canonical customer-facing state taxonomy (Rust surfaces).
//!
//! Single source of truth for the **8 customer states** that the malicious-vs-
//! vulnerable cluster (CLEANLIB-176 wire-shape + 177 policy overlay + 178
//! aesthetic) surfaces. The design contract lives at
//! `decisions/2026-06-12-cleanlib-178-state-aesthetic-mapping.md`; this module
//! is its executable form for the Rust render surfaces — `cleanlib-cli`,
//! `cleanlib-lsp` (CLEANLIB-209), and any consumer of `cleanlib-client`. The
//! TS extension / Python MCP / JS+Go+Py SDKs mirror this table in their own
//! languages, each with a contract test asserting the same wire→state map
//! (anti-drift, sister of the silent-schema-drift discipline).
//!
//! ## Why this lives in `cleanlib-client`, not `cleanlib-core`
//!
//! `cleanlib-core` is `publish = false`; the customer-state taxonomy is a
//! *presentation* concern consumed only by published render surfaces (the App
//! emits the wire `source`; it never renders a customer state). Keying on the
//! wire string (`Verdict.source: String`) — rather than `cleanlib-core`'s
//! `VerdictSource` enum — keeps this crate publishable to crates.io and avoids
//! a render-side dependency on the service-internal core crate.
//!
//! ## Design rules baked in (§0 of the spec — non-negotiable)
//!
//! 1. **Customer-language only** — wire/engine codenames never appear in
//!    `label()` / `copy()`.
//! 2. **Soft severity tokens** (dark-theme-safe); brand cyan `#50C0E0` is
//!    reserved for CLEAN.
//! 3. **Three derive tiers** (block / warn / clean) → exit codes (1 / 2 / 0).
//!
//! ## Derive-once + fail-closed
//!
//! Derive the state ONCE from the wire `source` ([`CustomerState::from_wire`]).
//! The App applies severity precedence server-side when it picks the single
//! `source`, so this map is 1:1 — no precedence is re-implemented here. An
//! unrecognized / future `source` fails CLOSED to `NotYetAssessed` (warn,
//! needs-review) — never silently Clean.

/// The three derive tiers — drive exit codes (block=1, warn=2, clean=0) and
/// the colour family, and map onto the universal ALLOW/WARN/DENY render bucket.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Tier {
    /// exit 1 — DENY. Customer must not install / must remove.
    Block,
    /// exit 2 — WARN. Review / upgrade (fail-closed for unknown).
    Warn,
    /// exit 0 — ALLOW. No known issues.
    Clean,
}

impl Tier {
    /// Process exit code for the CLI gate (block=1, warn=2, clean=0).
    pub fn exit_code(self) -> i32 {
        match self {
            Tier::Block => 1,
            Tier::Warn => 2,
            Tier::Clean => 0,
        }
    }
}

/// The 8 canonical customer-facing states, severity order (highest first) per
/// the BD-ratified ordering in §1: Blocked-by-policy, Compromised, Malicious,
/// Ransomware-linked, Actively-exploited, Vulnerable, Not-yet-assessed, Clean.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CustomerState {
    /// Customer's OWN policy rule blocked this package (operative gate).
    BlockedByPolicy,
    /// Tampered-with in a supply-chain attack (curated compromise list).
    Compromised,
    /// Known-malicious package (malware / typosquat).
    Malicious,
    /// Vulnerability tied to active ransomware campaigns.
    RansomwareLinked,
    /// Vulnerability being exploited in the wild (CISA KEV).
    ActivelyExploited,
    /// Has known CVEs (review + upgrade).
    Vulnerable,
    /// No verdict on file yet — fail-closed needs-review.
    NotYetAssessed,
    /// No known issues found.
    Clean,
}

impl CustomerState {
    /// Derive the customer state from the wire `source` string (the values in
    /// `crate::envelope::ALL_VERDICT_SOURCES`). Unknown / future variants fail
    /// CLOSED to `NotYetAssessed` (warn) — never silently Clean.
    ///
    /// Two variants carry a note:
    /// - `DM_THRESHOLD_BLOCK` → `BlockedByPolicy` (the customer's own rule).
    ///   The spec also routes a `DM_THRESHOLD_BLOCK` from the *curated*
    ///   supply-chain-compromise list (CLEANLIB-177) to `Compromised`, but that
    ///   distinction is carried by which rule fired, not by `source` alone, and
    ///   177 is not yet shipped. Until 177 lands + the App tags curated-list
    ///   blocks, every `DM_THRESHOLD_BLOCK` is the customer's policy. See
    ///   [`from_block_origin`](CustomerState::from_block_origin).
    /// - `VECTOR_VERDICT` is the legacy pre-176 full-eval source, preserved for
    ///   backward-compat. Post-176 the App projects findings into the specific
    ///   `CVE_FINDING*` variants, so a bare `VECTOR_VERDICT` reaching a render
    ///   surface is a legacy non-clean signal → `Vulnerable` (fail-safe).
    pub fn from_wire(source: &str) -> CustomerState {
        match source {
            "ALLOWED_NO_FINDINGS" => CustomerState::Clean,
            "CVE_FINDING" => CustomerState::Vulnerable,
            "CVE_FINDING_ON_KEV" => CustomerState::ActivelyExploited,
            "CVE_FINDING_ON_RANSOMWARE" => CustomerState::RansomwareLinked,
            "MALICIOUS_TRIAGE" => CustomerState::Malicious,
            "DM_THRESHOLD_BLOCK" => CustomerState::BlockedByPolicy,
            "INSUFFICIENT_DATA" => CustomerState::NotYetAssessed,
            // Legacy backward-compat — fail-safe to Vulnerable, never Clean.
            "VECTOR_VERDICT" => CustomerState::Vulnerable,
            // Unknown / future variant — fail CLOSED to needs-review.
            _ => CustomerState::NotYetAssessed,
        }
    }

    /// Same as [`from_wire`](CustomerState::from_wire) but lets the caller
    /// resolve the `DM_THRESHOLD_BLOCK` ambiguity when it knows the block
    /// origin. Use once CLEANLIB-177 ships and the App tags curated-list
    /// blocks: `curated_compromise = true` routes `DM_THRESHOLD_BLOCK` to
    /// `Compromised` instead of `BlockedByPolicy`.
    pub fn from_block_origin(source: &str, curated_compromise: bool) -> CustomerState {
        match (source, curated_compromise) {
            ("DM_THRESHOLD_BLOCK", true) => CustomerState::Compromised,
            _ => CustomerState::from_wire(source),
        }
    }

    /// Stable machine string for `--output json` `state` field + structured
    /// MCP/SDK fields. snake_case, customer-vocabulary, NOT the wire variant.
    pub fn as_str(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "blocked_by_policy",
            CustomerState::Compromised => "compromised",
            CustomerState::Malicious => "malicious",
            CustomerState::RansomwareLinked => "ransomware_linked",
            CustomerState::ActivelyExploited => "actively_exploited",
            CustomerState::Vulnerable => "vulnerable",
            CustomerState::NotYetAssessed => "not_yet_assessed",
            CustomerState::Clean => "clean",
        }
    }

    /// Customer-facing display label (Title-case, no codenames). §2 of spec.
    pub fn label(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "Blocked by policy",
            CustomerState::Compromised => "Compromised",
            CustomerState::Malicious => "Malicious",
            CustomerState::RansomwareLinked => "Ransomware-linked",
            CustomerState::ActivelyExploited => "Actively exploited",
            CustomerState::Vulnerable => "Vulnerable",
            CustomerState::NotYetAssessed => "Not yet assessed",
            CustomerState::Clean => "Clean",
        }
    }

    /// One-line, action-first customer copy (no codenames, no raw tier words).
    /// §2 of spec — verbatim.
    pub fn copy(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => {
                "Blocked by your organization's policy. Contact your security \
                 owner or request an exception."
            }
            CustomerState::Compromised => {
                "This version was tampered with in a supply-chain attack. Do \
                 not install — use a known-good version."
            }
            CustomerState::Malicious => {
                "Known-malicious package (malware / typosquat). Do not install."
            }
            CustomerState::RansomwareLinked => {
                "Carries a vulnerability tied to active ransomware campaigns. \
                 Upgrade before shipping."
            }
            CustomerState::ActivelyExploited => {
                "Has a vulnerability that's being exploited in the wild (on the \
                 U.S. CISA exploited list). Upgrade urgently."
            }
            CustomerState::Vulnerable => {
                "Has known vulnerabilities (CVEs). Review and upgrade to a \
                 fixed version."
            }
            CustomerState::NotYetAssessed => {
                "No verdict on file yet — treat as needs-review until assessed."
            }
            CustomerState::Clean => "No known issues found.",
        }
    }

    /// Derive tier (block / warn / clean). `NotYetAssessed` is fail-closed →
    /// Warn. Per §1 "Tier" column.
    pub fn tier(self) -> Tier {
        match self {
            CustomerState::BlockedByPolicy
            | CustomerState::Compromised
            | CustomerState::Malicious
            | CustomerState::RansomwareLinked
            | CustomerState::ActivelyExploited => Tier::Block,
            CustomerState::Vulnerable | CustomerState::NotYetAssessed => Tier::Warn,
            CustomerState::Clean => Tier::Clean,
        }
    }

    /// Process exit code for the CLI gate.
    pub fn exit_code(self) -> i32 {
        self.tier().exit_code()
    }

    /// CSS custom-property name for the soft severity token (extension + SDKs
    /// consume these for theming). §1 "Soft colour token" column.
    pub fn color_token(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "--cl-policy",
            CustomerState::Compromised => "--cl-compromised",
            CustomerState::Malicious => "--cl-malicious",
            CustomerState::RansomwareLinked => "--cl-ransomware",
            CustomerState::ActivelyExploited => "--cl-exploited",
            CustomerState::Vulnerable => "--cl-vulnerable",
            CustomerState::NotYetAssessed => "--cl-unknown",
            CustomerState::Clean => "--cl-clean",
        }
    }

    /// Soft severity hex (draft-ratified working palette, §5). Brand cyan for
    /// Clean; distinct mauve for policy so "your rule" reads apart from "our
    /// finding" reds.
    pub fn color_hex(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "#C77DBB",
            CustomerState::Compromised => "#D16D6A",
            CustomerState::Malicious => "#D9534F",
            CustomerState::RansomwareLinked => "#DB7B57",
            CustomerState::ActivelyExploited => "#E0934A",
            CustomerState::Vulnerable => "#D9A441",
            CustomerState::NotYetAssessed => "#7C8696",
            CustomerState::Clean => "#50C0E0",
        }
    }

    /// Text-surface emoji for MCP `human_message` + CLI text output. §1
    /// "MCP/CLI emoji" column. One concept per tier; states differentiate by
    /// label + colour, not a bespoke glyph family (§5 — reuse, don't cut).
    pub fn emoji(self) -> &'static str {
        match self {
            CustomerState::BlockedByPolicy => "🛑",
            CustomerState::Compromised => "",
            CustomerState::Malicious => "",
            CustomerState::RansomwareLinked => "🔴",
            CustomerState::ActivelyExploited => "🔴",
            CustomerState::Vulnerable => "⚠️",
            CustomerState::NotYetAssessed => "",
            CustomerState::Clean => "",
        }
    }

    /// All 8 states, severity order (highest first). For exhaustive contract
    /// tests + doc generation.
    pub fn all() -> [CustomerState; 8] {
        [
            CustomerState::BlockedByPolicy,
            CustomerState::Compromised,
            CustomerState::Malicious,
            CustomerState::RansomwareLinked,
            CustomerState::ActivelyExploited,
            CustomerState::Vulnerable,
            CustomerState::NotYetAssessed,
            CustomerState::Clean,
        ]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::envelope::ALL_VERDICT_SOURCES;

    // ── The wire→state mappings (the cross-surface contract) ────────────────
    #[test]
    fn wire_to_state_mapping_is_canonical() {
        use CustomerState::*;
        assert_eq!(CustomerState::from_wire("ALLOWED_NO_FINDINGS"), Clean);
        assert_eq!(CustomerState::from_wire("CVE_FINDING"), Vulnerable);
        assert_eq!(CustomerState::from_wire("CVE_FINDING_ON_KEV"), ActivelyExploited);
        assert_eq!(CustomerState::from_wire("CVE_FINDING_ON_RANSOMWARE"), RansomwareLinked);
        assert_eq!(CustomerState::from_wire("MALICIOUS_TRIAGE"), Malicious);
        assert_eq!(CustomerState::from_wire("DM_THRESHOLD_BLOCK"), BlockedByPolicy);
        assert_eq!(CustomerState::from_wire("INSUFFICIENT_DATA"), NotYetAssessed);
        assert_eq!(CustomerState::from_wire("VECTOR_VERDICT"), Vulnerable);
    }

    #[test]
    fn every_known_wire_source_maps_without_falling_through() {
        // Anti-drift: every value the envelope declares must have an explicit
        // mapping (not silently hit the fail-closed `_` arm). If 176/177 adds
        // a wire source, this fails until the map is extended.
        for &src in ALL_VERDICT_SOURCES {
            let state = CustomerState::from_wire(src);
            // ALLOWED_NO_FINDINGS is the only known source that may be Clean.
            if src != "ALLOWED_NO_FINDINGS" {
                assert_ne!(
                    state,
                    CustomerState::Clean,
                    "known non-clean source {src} mapped to Clean"
                );
            }
        }
    }

    #[test]
    fn unknown_source_fails_closed_to_needs_review() {
        assert_eq!(CustomerState::from_wire("SOME_FUTURE_VARIANT"), CustomerState::NotYetAssessed);
        assert_eq!(CustomerState::from_wire(""), CustomerState::NotYetAssessed);
        assert_ne!(CustomerState::from_wire("SOME_FUTURE_VARIANT"), CustomerState::Clean);
    }

    #[test]
    fn curated_compromise_routes_dm_block_to_compromised() {
        assert_eq!(
            CustomerState::from_block_origin("DM_THRESHOLD_BLOCK", true),
            CustomerState::Compromised
        );
        assert_eq!(
            CustomerState::from_block_origin("DM_THRESHOLD_BLOCK", false),
            CustomerState::BlockedByPolicy
        );
        assert_eq!(
            CustomerState::from_block_origin("CVE_FINDING", true),
            CustomerState::Vulnerable
        );
    }

    #[test]
    fn tier_and_exit_codes() {
        assert_eq!(CustomerState::Clean.exit_code(), 0);
        assert_eq!(CustomerState::Vulnerable.exit_code(), 2);
        assert_eq!(CustomerState::NotYetAssessed.exit_code(), 2); // fail-closed
        for s in [
            CustomerState::ActivelyExploited,
            CustomerState::RansomwareLinked,
            CustomerState::Malicious,
            CustomerState::Compromised,
            CustomerState::BlockedByPolicy,
        ] {
            assert_eq!(s.exit_code(), 1, "{s:?} must be block-tier");
        }
    }

    #[test]
    fn no_internal_codenames_in_customer_strings() {
        let banned = [
            "Vector", "VECTOR", "Tricorder", "DmThreshold", "DM_THRESHOLD",
            "CveFinding", "CVE_FINDING", "MaliciousTriage", "MALICIOUS_TRIAGE",
            "InsufficientData", "INSUFFICIENT_DATA", "vuln_xref", "mock", "fixture",
        ];
        for s in CustomerState::all() {
            for text in [s.label(), s.copy()] {
                for b in banned {
                    assert!(
                        !text.contains(b),
                        "codename {b:?} leaked into customer string {text:?} for {s:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn no_raw_tier_words_in_customer_copy() {
        for s in CustomerState::all() {
            for b in ["DENY", "WARN", "ALLOW"] {
                assert!(!s.copy().contains(b), "raw tier word {b} in copy for {s:?}");
                assert!(!s.label().contains(b), "raw tier word {b} in label for {s:?}");
            }
        }
    }

    #[test]
    fn every_state_has_complete_token_set() {
        for s in CustomerState::all() {
            assert!(!s.as_str().is_empty());
            assert!(!s.label().is_empty());
            assert!(!s.copy().is_empty());
            assert!(s.color_token().starts_with("--cl-"));
            assert!(s.color_hex().starts_with('#') && s.color_hex().len() == 7);
            assert!(!s.emoji().is_empty());
        }
    }

    #[test]
    fn clean_uses_brand_cyan_others_do_not() {
        assert_eq!(CustomerState::Clean.color_hex(), "#50C0E0");
        for s in CustomerState::all() {
            if s != CustomerState::Clean {
                assert_ne!(s.color_hex(), "#50C0E0", "{s:?} must not reuse brand cyan");
            }
        }
    }

    #[test]
    fn machine_strings_are_unique() {
        let mut seen = std::collections::HashSet::new();
        for s in CustomerState::all() {
            assert!(seen.insert(s.as_str()), "duplicate state string {}", s.as_str());
        }
    }
}