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
//! Risk-acceptance rule YAML emit per Client spec rev1 §11.1 +
//! phase-1-storage-architecture §3 customer-flow.
//!
//! Customer runs `cleanlib risk-accept` → CLI emits a YAML rule the
//! customer uploads to CDP admin UI to permit serve of a high-risk package
//! they need for legacy / vendor-pinned reasons.
//!
//! Output shape:
//! ```yaml
//! risk_accepted:
//!   - ecosystem: npm
//!     package: log4j-core
//!     version_range: "<2.15"
//!     justification: "Legacy system; vendor patch pending Q3 2026"
//!     proposed_by: "customer-admin@company.com"
//!     proposed_at: "2026-05-21T10:00:00Z"
//! ```
//!
//! Phase 1 hand-formats YAML rather than depending on `serde_yaml` (which
//! is deprecated upstream and would add ~30 transitive deps). The shape is
//! small + predictable; `yaml_escape` handles quote + backslash characters
//! in the justification (the only user-controlled string field).
//!
//! CLEANLIB-80: `ecosystem` field is emitted first so uploaded rules can be
//! disambiguated across ecosystems (a `requests` package exists in both
//! PyPI and RubyGems, `lodash` only in npm, etc.). Every sibling CLI
//! command (`verdict`, `scan`, `policy preview`, `audit`) already carries
//! an ecosystem argument — the rule YAML now matches that shape so the
//! policy engine can match unambiguously.

use chrono::{DateTime, Utc};

/// Risk-acceptance rule for one package + version-range in a given
/// ecosystem.
pub struct Rule {
    /// Package ecosystem — matches the ecosystem string used by the rest
    /// of the CLI (`npm`, `pypi`, `cargo`, `go`, `maven`, `nuget`,
    /// `rubygems`, `composer`). CLEANLIB-80.
    pub ecosystem: String,
    pub package: String,
    pub version_range: String,
    pub justification: String,
    /// Customer who's proposing the rule. Typically resolved from CDP user
    /// identity on the auth path; CLI accepts an explicit `--proposed-by`
    /// flag when the run-time auth context can't resolve it.
    pub proposed_by: Option<String>,
    pub proposed_at: DateTime<Utc>,
}

/// Emit the rule as a YAML document suitable for upload to CDP admin UI.
pub fn emit_yaml(rule: &Rule) -> String {
    let mut out = String::new();
    out.push_str("risk_accepted:\n");
    // CLEANLIB-80: ecosystem is emitted first (before `package`) so
    // customers reviewing rule YAML at a glance see the disambiguating
    // field before the potentially-cross-ecosystem package name.
    out.push_str(&format!("  - ecosystem: {}\n", yaml_inline(&rule.ecosystem)));
    out.push_str(&format!("    package: {}\n", yaml_inline(&rule.package)));
    out.push_str(&format!("    version_range: \"{}\"\n", yaml_escape(&rule.version_range)));
    out.push_str(&format!(
        "    justification: \"{}\"\n",
        yaml_escape(&rule.justification)
    ));
    if let Some(by) = &rule.proposed_by {
        out.push_str(&format!("    proposed_by: \"{}\"\n", yaml_escape(by)));
    }
    out.push_str(&format!(
        "    proposed_at: \"{}\"\n",
        rule.proposed_at.to_rfc3339()
    ));
    out
}

/// Inline-form for simple alphanumeric/dash/underscore strings (no quoting).
/// Falls back to double-quoted form if the string contains characters that
/// would need YAML escaping.
fn yaml_inline(s: &str) -> String {
    if s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | '@')) && !s.is_empty() {
        s.to_string()
    } else {
        format!("\"{}\"", yaml_escape(s))
    }
}

/// Escape characters that would break a double-quoted YAML string.
/// Per YAML 1.2 §5.7 double-quoted scalar escape rules — backslash and
/// double-quote are the load-bearing escapes; control chars are rare in
/// our inputs but covered defensively.
fn yaml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}

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

    fn fixed_ts() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 5, 21, 10, 0, 0).unwrap()
    }

    #[test]
    fn emit_minimal_rule_no_proposed_by() {
        let rule = Rule {
            ecosystem: "maven".to_string(),
            package: "log4j-core".to_string(),
            version_range: "<2.15".to_string(),
            justification: "Legacy system; vendor patch pending Q3 2026".to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        let expected = "risk_accepted:\n  - ecosystem: maven\n    package: log4j-core\n    version_range: \"<2.15\"\n    justification: \"Legacy system; vendor patch pending Q3 2026\"\n    proposed_at: \"2026-05-21T10:00:00+00:00\"\n";
        assert_eq!(out, expected);
    }

    #[test]
    fn emit_full_rule_with_proposed_by() {
        let rule = Rule {
            ecosystem: "maven".to_string(),
            package: "log4j-core".to_string(),
            version_range: "<2.15".to_string(),
            justification: "Legacy".to_string(),
            proposed_by: Some("admin@company.com".to_string()),
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        assert!(out.contains("proposed_by: \"admin@company.com\""));
    }

    #[test]
    fn justification_with_quotes_escaped() {
        let rule = Rule {
            ecosystem: "npm".to_string(),
            package: "left-pad".to_string(),
            version_range: "0.0.3".to_string(),
            justification: r#"customer said "we need this""#.to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        assert!(out.contains(r#"justification: "customer said \"we need this\"""#));
    }

    #[test]
    fn justification_with_backslash_escaped() {
        let rule = Rule {
            ecosystem: "npm".to_string(),
            package: "lodash".to_string(),
            version_range: "1.0".to_string(),
            justification: r"path\to\thing".to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        assert!(out.contains(r#"justification: "path\\to\\thing""#));
    }

    #[test]
    fn justification_with_newline_escaped() {
        let rule = Rule {
            ecosystem: "npm".to_string(),
            package: "x".to_string(),
            version_range: "*".to_string(),
            justification: "line1\nline2".to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        assert!(out.contains(r#"justification: "line1\nline2""#));
    }

    #[test]
    fn package_with_npm_scope_quoted() {
        // npm scoped packages like @my-org/foo have / and @ which ARE in
        // the inline-form allowed set, so they stay unquoted.
        let rule = Rule {
            ecosystem: "npm".to_string(),
            package: "@my-org/foo".to_string(),
            version_range: "^1.0".to_string(),
            justification: "x".to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        assert!(out.contains("package: @my-org/foo\n"));
    }

    #[test]
    fn package_with_space_gets_quoted() {
        let rule = Rule {
            ecosystem: "npm".to_string(),
            package: "weird package".to_string(),
            version_range: "1".to_string(),
            justification: "x".to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        assert!(out.contains("package: \"weird package\"\n"));
    }

    /// CLEANLIB-80 regression guard: the emitted YAML MUST carry an
    /// `ecosystem` field so an uploaded rule can be disambiguated when
    /// the same package name exists in multiple ecosystems (e.g.
    /// `requests` in both PyPI and RubyGems).
    #[test]
    fn ecosystem_field_is_emitted_first() {
        let rule = Rule {
            ecosystem: "pypi".to_string(),
            package: "requests".to_string(),
            version_range: "2.31.0".to_string(),
            justification: "vendor pin".to_string(),
            proposed_by: None,
            proposed_at: fixed_ts(),
        };
        let out = emit_yaml(&rule);
        // Ecosystem is emitted before package — reviewers see the
        // disambiguating field before the potentially-cross-ecosystem
        // package name.
        let eco_pos = out.find("ecosystem: pypi").expect("ecosystem field present");
        let pkg_pos = out.find("package: requests").expect("package field present");
        assert!(eco_pos < pkg_pos, "ecosystem must precede package in YAML");
    }
}