cleanlib-client 0.3.0

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
//! `VerdictEnvelopeV1` + `ReasonCode` — schema-locked mirror of
//! `@cleanstart/cleanlib-sdk@0.4.1` (tarball sha-1
//! `b5f00c160907a6ea1f490f14a9bda6f6de34b8b6`).
//!
//! Sister of:
//! - sdk-js  `dist/reason-codes.js` + `dist/verdict-envelope.schema.json`
//! - sdk-py  `cleanlib_sdk/reason_codes.py`
//! - sdk-go  `reason_codes.go`
//!
//! Drift between any of the four SDK consumers is a CI failure;
//! `cleanlib-contract-fixtures` v1.0.0 verifies byte-identical
//! `(status, reason_code)` across all 4 implementations.
//!
//! Freshness-precedence rule (ratified 2026-05-28; binding via App dispatch §4
//! + Client dispatch §2.3): when the substance-driving signal's
//! `availability == "degraded_stale"`, the substance-derived status tier is
//! PRESERVED and the `reason_code` OVERRIDES to `VERDICT_DEGRADED_STALE`.
//! Server-side `VERDICT_DEGRADED_STALE` is architecturally distinct from the
//! client-side `LIVE_DEGRADED` cache-fallback state (extension status bar +
//! Cli7 offline mode).

use serde::{Deserialize, Serialize};

/// Tri-state envelope status tier — sister of sdk-js Literal type
/// `'ALLOW' | 'WARN' | 'DENY'`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum Status {
    #[serde(rename = "ALLOW")]
    Allow,
    #[serde(rename = "WARN")]
    Warn,
    #[serde(rename = "DENY")]
    Deny,
}

impl Status {
    /// Canonical wire-format string — what App emits + what every other SDK
    /// asserts on.
    pub fn as_str(&self) -> &'static str {
        match self {
            Status::Allow => "ALLOW",
            Status::Warn => "WARN",
            Status::Deny => "DENY",
        }
    }
}

impl std::fmt::Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Canonical 15-value `ReasonCode` registry — Rust mirror of sdk-js v0.4.1
/// `dist/reason-codes.js`. Drift = CI failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum ReasonCode {
    // ─── Status outcomes (verdict-tier reasons) ──────────────────────────
    #[serde(rename = "VERDICT_CLEAN")]
    VerdictClean,
    #[serde(rename = "VERDICT_RECOMMENDED_VERSION_NEWER")]
    VerdictRecommendedVersionNewer,
    #[serde(rename = "VERDICT_ABANDONED")]
    VerdictAbandoned,
    #[serde(rename = "VERDICT_LOW_TRUST")]
    VerdictLowTrust,
    /// CLEANLIB-511 (B2) / 503: unified reason for a VECTOR_VERDICT CVE finding
    /// at LOW/MEDIUM/HIGH severity — retires the incoherent per-severity codes
    /// (VERDICT_CLEAN on LOW = "no findings", VERDICT_ABANDONED on MEDIUM =
    /// "unmaintained", VERDICT_LOW_TRUST on HIGH) which asserted facts unrelated
    /// to "has a CVE". Severity is carried in `rich_data.severity`.
    /// VERDICT_ABANDONED stays reserved for the genuine `abandonment_score`
    /// signal (derive_status), VERDICT_EXPLOITATION_CRITICAL for CRITICAL.
    #[serde(rename = "VERDICT_CVE_FOUND")]
    VerdictCveFound,
    /// CLEANLIB S1 (cycle-22, closes PM 731999 §1): canonical reason for a
    /// not-yet-assessed package. `INSUFFICIENT_DATA` fails closed to WARN +
    /// `VERDICT_NOT_YET_ASSESSED` — replaces the cycle-21 D1 `VERDICT_CLEAN`
    /// placeholder (status-correct but reason-incoherent, Discipline #60).
    #[serde(rename = "VERDICT_NOT_YET_ASSESSED")]
    VerdictNotYetAssessed,
    /// Server-side substrate freshness — substance-derived tier preserved,
    /// reason overridden to surface staleness. Distinct from client-side
    /// `LIVE_DEGRADED` cache-fallback (extension status bar; Cli7 offline mode).
    #[serde(rename = "VERDICT_DEGRADED_STALE")]
    VerdictDegradedStale,
    #[serde(rename = "VERDICT_HAS_REMEDIATION")]
    VerdictHasRemediation,
    #[serde(rename = "VERDICT_KEV_LISTED")]
    VerdictKevListed,
    /// CLEANLIB-176: package named in ransomware campaigns
    /// (`CVE_FINDING_ON_RANSOMWARE` source projection). Semantically distinct
    /// from KEV — a CVE can be ransomware-linked without being CISA-KEV-listed
    /// and vice-versa; conflating them defeats the 176 differentiation goal.
    /// Cross-SDK + Threat ratification PENDING (see CLEANLIB-176 comment 658233).
    #[serde(rename = "VERDICT_RANSOMWARE_LISTED")]
    VerdictRansomwareListed,
    #[serde(rename = "VERDICT_EXPLOITATION_CRITICAL")]
    VerdictExploitationCritical,
    /// CLEANLIB-176: confirmed/likely-malicious package (`MALICIOUS_TRIAGE`
    /// source projection — typosquat / backdoor / protestware). Distinct from
    /// `VERDICT_EXPLOITATION_CRITICAL` (a *CVE* being actively exploited):
    /// malicious means remove + audit + rotate, not upgrade.
    /// Cross-SDK + Threat ratification PENDING (see CLEANLIB-176 comment 658233).
    #[serde(rename = "VERDICT_MALICIOUS")]
    VerdictMalicious,
    #[serde(rename = "VERDICT_OBFUSCATED")]
    VerdictObfuscated,
    #[serde(rename = "VERDICT_DENY_LIST")]
    VerdictDenyList,
    /// CLEANLIB-518 (§3): the App could not resolve the requested semver range
    /// to a concrete version (`source_state = RANGE_NOT_RESOLVED`, CLEANLIB-513).
    /// Distinct from `VERDICT_NOT_YET_ASSESSED` — the package is not un-assessed,
    /// the *range* is unresolved, so the customer must pin a concrete version.
    /// Fixes the CLI banner↔body contradiction where a range-not-resolved verdict
    /// rendered the "❔ Not yet assessed" banner while the reasoning body said the
    /// opposite. Fails CLOSED to WARN (an unresolved range is not an ALLOW).
    #[serde(rename = "VERDICT_RANGE_NOT_RESOLVED")]
    VerdictRangeNotResolved,

    // ─── Client-transport reasons ────────────────────────────────────────
    #[serde(rename = "CLIENT_NETWORK_UNREACHABLE")]
    ClientNetworkUnreachable,
    #[serde(rename = "CLIENT_AUTH_FAILED")]
    ClientAuthFailed,
    #[serde(rename = "CLIENT_BEARER_MISSING")]
    ClientBearerMissing,
    #[serde(rename = "CLIENT_RATE_LIMITED")]
    ClientRateLimited,

    // ─── Domain — 404 from /api/v1/remediation/:eco/:name ───────────────
    #[serde(rename = "REMEDIATION_NOT_FOUND")]
    RemediationNotFound,
}

impl ReasonCode {
    /// Canonical wire-format string — what App emits + what every other SDK
    /// asserts on.
    pub fn as_str(&self) -> &'static str {
        match self {
            ReasonCode::VerdictClean => "VERDICT_CLEAN",
            ReasonCode::VerdictRecommendedVersionNewer => "VERDICT_RECOMMENDED_VERSION_NEWER",
            ReasonCode::VerdictAbandoned => "VERDICT_ABANDONED",
            ReasonCode::VerdictLowTrust => "VERDICT_LOW_TRUST",
            ReasonCode::VerdictCveFound => "VERDICT_CVE_FOUND",
            ReasonCode::VerdictNotYetAssessed => "VERDICT_NOT_YET_ASSESSED",
            ReasonCode::VerdictDegradedStale => "VERDICT_DEGRADED_STALE",
            ReasonCode::VerdictHasRemediation => "VERDICT_HAS_REMEDIATION",
            ReasonCode::VerdictKevListed => "VERDICT_KEV_LISTED",
            ReasonCode::VerdictRansomwareListed => "VERDICT_RANSOMWARE_LISTED",
            ReasonCode::VerdictExploitationCritical => "VERDICT_EXPLOITATION_CRITICAL",
            ReasonCode::VerdictMalicious => "VERDICT_MALICIOUS",
            ReasonCode::VerdictObfuscated => "VERDICT_OBFUSCATED",
            ReasonCode::VerdictDenyList => "VERDICT_DENY_LIST",
            ReasonCode::VerdictRangeNotResolved => "VERDICT_RANGE_NOT_RESOLVED",
            ReasonCode::ClientNetworkUnreachable => "CLIENT_NETWORK_UNREACHABLE",
            ReasonCode::ClientAuthFailed => "CLIENT_AUTH_FAILED",
            ReasonCode::ClientBearerMissing => "CLIENT_BEARER_MISSING",
            ReasonCode::ClientRateLimited => "CLIENT_RATE_LIMITED",
            ReasonCode::RemediationNotFound => "REMEDIATION_NOT_FOUND",
        }
    }
}

impl std::fmt::Display for ReasonCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// All 20 canonical reason-code values — consumed by drift-check CI.
/// CLEANLIB-176 added `VERDICT_RANSOMWARE_LISTED` + `VERDICT_MALICIOUS` (15→17);
/// S1 (cycle-22) added VERDICT_NOT_YET_ASSESSED (17→18); CLEANLIB-511(B2)/503 added VERDICT_CVE_FOUND (18→19);
/// CLEANLIB-518(§3) added VERDICT_RANGE_NOT_RESOLVED (19→20). The
/// three external SDKs (js/py/go) land these in coordinated follow-on PRs.
pub const ALL_REASON_CODES: &[ReasonCode] = &[
    ReasonCode::VerdictClean,
    ReasonCode::VerdictRecommendedVersionNewer,
    ReasonCode::VerdictAbandoned,
    ReasonCode::VerdictLowTrust,
    ReasonCode::VerdictCveFound,
    ReasonCode::VerdictNotYetAssessed,
    ReasonCode::VerdictDegradedStale,
    ReasonCode::VerdictHasRemediation,
    ReasonCode::VerdictKevListed,
    ReasonCode::VerdictRansomwareListed,
    ReasonCode::VerdictExploitationCritical,
    ReasonCode::VerdictMalicious,
    ReasonCode::VerdictObfuscated,
    ReasonCode::VerdictDenyList,
    ReasonCode::VerdictRangeNotResolved,
    ReasonCode::ClientNetworkUnreachable,
    ReasonCode::ClientAuthFailed,
    ReasonCode::ClientBearerMissing,
    ReasonCode::ClientRateLimited,
    ReasonCode::RemediationNotFound,
];

/// Canonical wire-strings for the verdict `source` field — Rust mirror of
/// `cleanlib_core::VerdictSource` SCREAMING_SNAKE serde output. The first four
/// are the cycle-≤16 originals; the last four are the CLEANLIB-176 projection
/// variants that let customers separate "has CVEs" (upgrade) from "actively
/// exploited" (KEV) / "ransomware-linked" / "malicious" (remove+audit+rotate).
/// Used by [`crate::verdict_to_envelope_v1`] to refine the reason_code by
/// source while preserving the label-derived status tier.
pub const ALL_VERDICT_SOURCES: &[&str] = &[
    "ALLOWED_NO_FINDINGS",
    "VECTOR_VERDICT",
    "DM_THRESHOLD_BLOCK",
    "INSUFFICIENT_DATA",
    "CVE_FINDING",
    "CVE_FINDING_ON_KEV",
    "CVE_FINDING_ON_RANSOMWARE",
    "MALICIOUS_TRIAGE",
];

/// `VerdictEnvelopeV1` — parsed shape of the `verdict-envelope.v1.json`
/// schema. Top-level fields are required; rich sub-objects are sparse and
/// `#[serde(default)]`-tolerant so the SDK can consume partial responses
/// during cycle-N spec evolution without forcing a recompile.
///
/// Sister of:
/// - sdk-js  `VerdictEnvelopeV1Schema` (zod)
/// - sdk-py  no struct (dict[str, Any] in Python)
/// - sdk-go  `map[string]any` (loose) — but Rust gets a typed struct.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VerdictEnvelopeV1 {
    pub status: String,
    pub reason_code: String,
    pub human_message: String,
    pub as_of: String,
    /// CLEANLIB-505 (III): full-nanosecond `as_of`, dual-emitted alongside the
    /// (possibly µs-truncated) `as_of` string. Additive migration-window field
    /// (A3-style) — Python truncates `as_of` to µs at datetime-parse, so the
    /// raw ns timestamp is carried here as a string for consumers that need
    /// sub-µs precision. Rust preserves ns in `as_of` already, so this mirrors
    /// it. `skip_serializing_if = None` → byte-identical v1 when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub as_of_ns: Option<String>,

    #[serde(default)]
    pub rich_data: Option<serde_json::Value>,
    #[serde(default)]
    pub remediation: Option<serde_json::Value>,
    #[serde(default)]
    pub exploitability: Option<serde_json::Value>,
    /// CLEANLIB-104 App-3.1 Gate M3: non-Optional per the design doc §3.3
    /// exit criterion ("derive_status.rs line 57 stops using as_ref on
    /// availability"). `#[serde(default)]` gives `Value::Null` on absent-key
    /// payloads — fail-open: consumers see a defaulted block, not an
    /// unwrap-panic. `derive_status.rs` uses `Some(&envelope.availability)`
    /// against the untyped JSON-Value helpers (see line 57).
    ///
    /// `skip_serializing_if = "Value::is_null"` preserves the wire byte-
    /// identity on happy-path envelopes: when the adapter passes through a
    /// default `AvailabilityBlock` (degraded_stale=false), the envelope
    /// serializes as `Null` and the field is omitted — matching the pre-M3
    /// `Option<Value>::None` shape.
    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
    pub availability: serde_json::Value,
}

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

    #[test]
    fn parses_minimal_envelope() {
        let json = r#"{
            "status": "ALLOW",
            "reason_code": "VERDICT_CLEAN",
            "human_message": "ok",
            "as_of": "2026-05-28"
        }"#;
        let env: VerdictEnvelopeV1 = serde_json::from_str(json).unwrap();
        assert_eq!(env.status, "ALLOW");
        assert_eq!(env.reason_code, "VERDICT_CLEAN");
        assert!(env.rich_data.is_none());
        assert!(env.remediation.is_none());
        assert!(env.exploitability.is_none());
        // CLEANLIB-104 M3: availability is non-Optional; absent JSON key
        // deserializes to `Value::Null` (the serde default for
        // `serde_json::Value`).
        assert!(env.availability.is_null());
    }

    #[test]
    fn all_20_reason_codes_present() {
        // Drift-check sister of sdk-py ALL_REASON_CODES + sdk-go AllReasonCodes.
        // CLEANLIB-176: 15 → 17 (+VERDICT_RANSOMWARE_LISTED +VERDICT_MALICIOUS).
        // S1 (cycle-22, PM 731999 §1): 17 → 18 (+VERDICT_NOT_YET_ASSESSED).
        // CLEANLIB-511(B2)/503: 18 → 19 (+VERDICT_CVE_FOUND).
        // CLEANLIB-518(§3): 19 → 20 (+VERDICT_RANGE_NOT_RESOLVED).
        assert_eq!(ALL_REASON_CODES.len(), 20);
        assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictCveFound));
        assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictNotYetAssessed));
        assert!(ALL_REASON_CODES.contains(&ReasonCode::VerdictRangeNotResolved));
    }

    #[test]
    fn all_verdict_sources_recognized() {
        // CLEANLIB-176: the SDK must recognize all 8 wire-strings for the
        // verdict `source` field (4 originals + 4 projection variants) so it
        // never silently misclassifies a known source as unknown.
        assert_eq!(ALL_VERDICT_SOURCES.len(), 8);
        assert!(ALL_VERDICT_SOURCES.contains(&"CVE_FINDING_ON_KEV"));
        assert!(ALL_VERDICT_SOURCES.contains(&"CVE_FINDING_ON_RANSOMWARE"));
        assert!(ALL_VERDICT_SOURCES.contains(&"MALICIOUS_TRIAGE"));
    }

    #[test]
    fn reason_code_string_roundtrip() {
        for rc in ALL_REASON_CODES {
            let s = serde_json::to_string(rc).unwrap();
            let back: ReasonCode = serde_json::from_str(&s).unwrap();
            assert_eq!(&back, rc);
            // as_str() matches serde wire format (quoted JSON string).
            assert_eq!(format!("\"{}\"", rc.as_str()), s);
        }
    }

    #[test]
    fn status_string_roundtrip() {
        for st in [Status::Allow, Status::Warn, Status::Deny] {
            let s = serde_json::to_string(&st).unwrap();
            let back: Status = serde_json::from_str(&s).unwrap();
            assert_eq!(back, st);
            assert_eq!(format!("\"{}\"", st.as_str()), s);
        }
    }
}