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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! `CleanLibraryError` hierarchy per Client spec rev1 §2.3 + Rev 2 amendment §2.
//! Mirrors App Rev 4 §9.2 reason-code enum surfaced via `X-CleanLibrary-Reason`
//! response header.

use thiserror::Error;

/// Top-level error type for cleanlib-client operations.
/// Mirrors Rev 1 §2.3 mapping table.
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum CleanLibraryError {
    #[error("config error: {0}")]
    Config(#[from] crate::config::ConfigError),

    /// Policy DENY — `403` + `POLICY_DENY_VERDICT` / `POLICY_DENY_RULE_EXPLICIT`,
    /// or `451 Unavailable For Legal Reasons` (npm ecosystem alias).
    #[error("policy deny [{reason_code}]: {message}")]
    PolicyDeny { reason_code: String, message: String },

    /// `403` + `INTEGRITY_FAILURE` — package hash mismatch on serve path
    /// (security incident; App refuses serve).
    #[error("integrity failure [{reason_code}]: {message}")]
    IntegrityFailure { reason_code: String, message: String },

    /// `429 Too Many Requests` + `Retry-After` header.
    #[error("rate limit exceeded; retry after {retry_after_seconds}s ({message})")]
    RateLimitExceeded { retry_after_seconds: u64, message: String },

    /// `403` + `RISK_ACCEPTANCE_REQUIRED` — policy permits ALLOW but customer
    /// hasn't signed risk-acceptance for this package/version. Customer should
    /// emit a rule via `cleanlib risk-accept` and upload to CDP admin UI.
    #[error("risk acceptance required [{reason_code}]: {message}")]
    RiskAcceptanceRequired {
        reason_code: String,
        message: String,
        guidance: Option<String>,
        docs_url: Option<String>,
    },

    /// `401` or `403` + `KEY_INVALID` / `KEY_EXPIRED` / `KEY_SCOPE_INSUFFICIENT`.
    #[error("authentication failed [{reason_code}]: {message}")]
    Authentication { reason_code: String, message: String },

    /// `403` + `INSUFFICIENT_DATA_FAIL_CLOSED` — verdict unavailable + customer
    /// policy fails closed on missing data.
    #[error("insufficient data [{reason_code}]: {message}")]
    InsufficientData { reason_code: String, message: String },

    /// CLEANLIB-657 (CX-8): a scan/fix run could not evaluate one or more
    /// coordinates (outage / TLS / 5xx / unreachable). NOT a verdict — the gate
    /// did not fully run; callers must never read this as clean coverage.
    #[error("coverage incomplete [{reason_code}]: {message}")]
    CoverageIncomplete { reason_code: String, message: String },

    /// CLEANLIB-657 (CX-8): a signed attestation was present but failed
    /// verification (signature / key / canonical-form mismatch).
    #[error("attestation invalid [{reason_code}]: {message}")]
    AttestationInvalid { reason_code: String, message: String },

    /// `404 Not Found` — package not in catalog + ingest declined or unavailable.
    #[error("package not found: {0}")]
    PackageNotFound(String),

    /// `5xx` — server error. `retryable=true` for 502/503/504.
    #[error("server error {status}: {message}")]
    ServerError { status: u16, message: String, retryable: bool },

    /// CLEANLIB-536: an RFC 9457 `application/problem+json` structured error.
    /// Carries the App's problem document — the standard
    /// `type`/`title`/`status`/`detail`/`instance` members plus the CLEANLIB-536
    /// extensions `reason_class` (the machine-stable branch key —
    /// `not_ingested` / `dependency_degraded` / `permanently_blocked` /
    /// `service_unavailable`), `retryable`, `selfHealing`, and `resolution`.
    /// Consumers branch on `problem.reason_class` and honor `problem.retryable`
    /// rather than scraping status codes or the raw body. Emitted when the App
    /// response is `application/problem+json`; legacy header/status responses
    /// keep the variants above.
    #[error("{problem}")]
    Problem { problem: ProblemDetails },

    /// Network / TLS / timeout / DNS — pre-response transport-layer failure.
    #[error("transport error: {0}")]
    Transport(#[from] TransportError),

    /// Response body parse failure (malformed JSON, schema mismatch).
    #[error("parse error: {0}")]
    Parse(String),
}

/// CLEANLIB-536: RFC 9457 `application/problem+json` problem document (reader
/// side). Mirrors `cleanlib-app::problem::ProblemDetails` as a TOLERANT reader —
/// every field is defaulted and unknown members are ignored (no
/// `deny_unknown_fields`), so a new App extension never breaks parsing. Standard
/// RFC 9457 members (`type`/`title`/`status`/`detail`/`instance`) plus the
/// CLEANLIB-536 extensions.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(default)]
pub struct ProblemDetails {
    /// The `type` URI (`https://cleanlibrary.dev/problems/<slug>`). The RFC 9457
    /// primary identifier; presence marks a well-formed problem document.
    #[serde(rename = "type")]
    pub type_uri: String,
    /// Short human-readable summary.
    pub title: String,
    /// HTTP status echoed in the body.
    pub status: u16,
    /// Longer human-readable explanation (optional per RFC 9457).
    pub detail: Option<String>,
    /// URI identifying the specific occurrence (optional).
    pub instance: Option<String>,
    /// Machine-stable branch key (`not_ingested` / `dependency_degraded` /
    /// `permanently_blocked` / `service_unavailable`). Prefer this over `status`
    /// for programmatic branching.
    pub reason_class: String,
    /// Whether retrying the SAME request could succeed.
    pub retryable: bool,
    /// Present when the App is actively self-healing the degraded dependency.
    #[serde(rename = "selfHealing")]
    pub self_healing: Option<bool>,
    /// Suggested caller action for permanently-blocked / actionable problems.
    pub resolution: Option<String>,
}

impl std::fmt::Display for ProblemDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let class = if self.reason_class.is_empty() {
            "problem"
        } else {
            self.reason_class.as_str()
        };
        write!(f, "[{}] {}", class, self.title)?;
        if let Some(detail) = &self.detail {
            write!(f, ": {}", detail)?;
        }
        Ok(())
    }
}

/// Parse an `application/problem+json` body (CLEANLIB-536) into
/// [`ProblemDetails`], returning `None` when the body is absent or is not a
/// problem document. A body is treated as a problem document when the response
/// `Content-Type` is `application/problem+json` OR (defensively, in case a proxy
/// strips the content-type) the parsed `type` URI is under the canonical
/// `https://cleanlibrary.dev/problems/` base. A bare JSON error body that merely
/// happens to carry a `type` field is NOT misclassified.
pub fn parse_problem_details(
    headers: &reqwest::header::HeaderMap,
    body: &str,
) -> Option<ProblemDetails> {
    let ct_is_problem = headers
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .map(|ct| ct.starts_with("application/problem+json"))
        .unwrap_or(false);
    let problem: ProblemDetails = serde_json::from_str(body).ok()?;
    if problem.type_uri.is_empty() {
        return None;
    }
    if ct_is_problem || problem.type_uri.starts_with("https://cleanlibrary.dev/problems/") {
        Some(problem)
    } else {
        None
    }
}

#[derive(Debug, Error)]
pub enum TransportError {
    #[error("network: {0}")]
    Network(#[source] reqwest::Error),

    #[error("invalid endpoint URL: {0}")]
    InvalidUrl(String),

    #[error("TLS required; refusing plaintext endpoint {0} (localhost exempt for testing)")]
    TlsRequired(String),

    #[error("timeout")]
    Timeout,
}

impl CleanLibraryError {
    /// True if a transient retry could plausibly succeed. Callers may use
    /// this to gate retry/backoff logic. Per Rev 1 §2.3 + App Rev 4 §9.2.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::ServerError { retryable, .. } => *retryable,
            Self::Transport(TransportError::Timeout) => true,
            Self::Transport(TransportError::Network(_)) => true,
            Self::RateLimitExceeded { .. } => true,
            _ => false,
        }
    }

    /// Reason code from App's `X-CleanLibrary-Reason` header, if any.
    pub fn reason_code(&self) -> Option<&str> {
        match self {
            Self::PolicyDeny { reason_code, .. }
            | Self::IntegrityFailure { reason_code, .. }
            | Self::RiskAcceptanceRequired { reason_code, .. }
            | Self::Authentication { reason_code, .. }
            | Self::InsufficientData { reason_code, .. } => Some(reason_code),
            _ => None,
        }
    }
}

/// Map HTTP `status` + headers + body into a `CleanLibraryError` variant.
/// Reads `X-CleanLibrary-Reason` header per App Rev 4 §9.2 reason codes.
pub fn from_http(
    status: u16,
    headers: &reqwest::header::HeaderMap,
    body: &str,
) -> CleanLibraryError {
    // CLEANLIB-536: an RFC 9457 `application/problem+json` response is surfaced
    // as the structured `Problem` variant (type/title/detail/reason_class/
    // retryable/…) so consumers branch on `reason_class` rather than scraping the
    // status or the raw body. Legacy header/status responses fall through to the
    // reason-code routing below (back-compat).
    if let Some(problem) = parse_problem_details(headers, body) {
        return CleanLibraryError::Problem { problem };
    }

    let reason_code = headers
        .get("X-CleanLibrary-Reason")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("UNKNOWN")
        .to_string();
    let message = if body.is_empty() {
        format!("HTTP {}", status)
    } else {
        body.to_string()
    };

    match (status, reason_code.as_str()) {
        (401, _) => CleanLibraryError::Authentication { reason_code, message },
        (403, "KEY_INVALID" | "KEY_EXPIRED" | "KEY_SCOPE_INSUFFICIENT") => {
            CleanLibraryError::Authentication { reason_code, message }
        }
        (403, "POLICY_DENY_VERDICT" | "POLICY_DENY_RULE_EXPLICIT") | (451, _) => {
            CleanLibraryError::PolicyDeny { reason_code, message }
        }
        (403, "RISK_ACCEPTANCE_REQUIRED") => CleanLibraryError::RiskAcceptanceRequired {
            reason_code,
            message,
            guidance: None,
            docs_url: Some("https://docs.cleanlibrary.io/risk-acceptance".to_string()),
        },
        (403, "INTEGRITY_FAILURE") => CleanLibraryError::IntegrityFailure { reason_code, message },
        (403, "INSUFFICIENT_DATA_FAIL_CLOSED") => {
            CleanLibraryError::InsufficientData { reason_code, message }
        }
        (429, _) => {
            let retry_after_seconds = headers
                .get("Retry-After")
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.parse().ok())
                .unwrap_or(60);
            CleanLibraryError::RateLimitExceeded { retry_after_seconds, message }
        }
        (404, _) => CleanLibraryError::PackageNotFound(message),
        (500..=599, _) => CleanLibraryError::ServerError {
            status,
            message,
            retryable: matches!(status, 502 | 503 | 504),
        },
        _ => CleanLibraryError::ServerError {
            status,
            message,
            retryable: false,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use reqwest::header::{HeaderMap, HeaderValue};

    fn headers_with_reason(code: &str) -> HeaderMap {
        let mut h = HeaderMap::new();
        h.insert("X-CleanLibrary-Reason", HeaderValue::from_str(code).unwrap());
        h
    }

    fn problem_headers() -> HeaderMap {
        let mut h = HeaderMap::new();
        h.insert(
            reqwest::header::CONTENT_TYPE,
            HeaderValue::from_static("application/problem+json"),
        );
        h
    }

    // ─── CLEANLIB-536 RFC 9457 problem+json ─────────────────────────────────

    const NOT_INGESTED_BODY: &str = r#"{
        "type": "https://cleanlibrary.dev/problems/not-ingested",
        "title": "Package not in CleanLibrary catalog",
        "status": 404,
        "detail": "npm/left-pad@99.0.0 has not been ingested",
        "reason_class": "not_ingested",
        "retryable": false
    }"#;

    #[test]
    fn problem_json_maps_to_structured_problem() {
        let err = from_http(404, &problem_headers(), NOT_INGESTED_BODY);
        match err {
            CleanLibraryError::Problem { problem } => {
                assert_eq!(problem.type_uri, "https://cleanlibrary.dev/problems/not-ingested");
                assert_eq!(problem.reason_class, "not_ingested");
                assert_eq!(problem.status, 404);
                assert!(!problem.retryable);
                assert_eq!(problem.detail.as_deref(), Some("npm/left-pad@99.0.0 has not been ingested"));
            }
            other => panic!("expected Problem, got {other:?}"),
        }
    }

    #[test]
    fn problem_json_degraded_is_retryable_with_selfhealing() {
        let body = r#"{
            "type": "https://cleanlibrary.dev/problems/dependency-degraded-self-healing",
            "title": "Upstream advisories degraded — self-healing",
            "status": 503,
            "reason_class": "dependency_degraded",
            "retryable": true,
            "selfHealing": true
        }"#;
        match from_http(503, &problem_headers(), body) {
            CleanLibraryError::Problem { problem } => {
                assert_eq!(problem.reason_class, "dependency_degraded");
                assert!(problem.retryable);
                assert_eq!(problem.self_healing, Some(true));
            }
            other => panic!("expected Problem, got {other:?}"),
        }
    }

    #[test]
    fn problem_json_tolerates_unknown_extension_fields() {
        let body = r#"{
            "type": "https://cleanlibrary.dev/problems/permanently-blocked",
            "title": "Verdict requires action to resolve",
            "status": 422,
            "reason_class": "permanently_blocked",
            "retryable": false,
            "resolution": "upgrade to >=1.2.3",
            "future_extension_field": {"nested": [1,2,3]}
        }"#;
        match from_http(422, &problem_headers(), body) {
            CleanLibraryError::Problem { problem } => {
                assert_eq!(problem.reason_class, "permanently_blocked");
                assert_eq!(problem.resolution.as_deref(), Some("upgrade to >=1.2.3"));
            }
            other => panic!("expected Problem, got {other:?}"),
        }
    }

    #[test]
    fn problem_type_uri_sniff_without_content_type() {
        // Defensive: a proxy strips the content-type but the body is a canonical
        // problem doc → still surfaced as Problem.
        let err = from_http(404, &HeaderMap::new(), NOT_INGESTED_BODY);
        assert!(matches!(err, CleanLibraryError::Problem { .. }));
    }

    #[test]
    fn non_problem_body_falls_through_to_legacy_routing() {
        // A plain JSON error body with a `type` field that is NOT a problems URI
        // must NOT be misclassified — legacy header/status routing wins.
        let body = r#"{"type": "some_other_thing", "message": "nope"}"#;
        let err = from_http(401, &HeaderMap::new(), body);
        assert!(matches!(err, CleanLibraryError::Authentication { .. }));
    }

    #[test]
    fn legacy_reason_header_still_maps_without_problem_json() {
        // Back-compat: no problem+json → the 429 rate-limit path is unchanged.
        let err = from_http(429, &headers_with_reason("RATE_LIMIT"), "slow down");
        assert!(matches!(err, CleanLibraryError::RateLimitExceeded { .. }));
    }

    #[test]
    fn maps_401_to_auth() {
        let err = from_http(401, &HeaderMap::new(), "bad token");
        assert!(matches!(err, CleanLibraryError::Authentication { .. }));
    }

    #[test]
    fn maps_403_policy_deny_verdict() {
        let err = from_http(403, &headers_with_reason("POLICY_DENY_VERDICT"), "verdict denies");
        assert!(matches!(err, CleanLibraryError::PolicyDeny { .. }));
        assert_eq!(err.reason_code(), Some("POLICY_DENY_VERDICT"));
    }

    #[test]
    fn maps_451_npm_legal_alias_to_policy_deny() {
        let err = from_http(451, &HeaderMap::new(), "");
        assert!(matches!(err, CleanLibraryError::PolicyDeny { .. }));
    }

    #[test]
    fn maps_403_risk_acceptance_required() {
        let err = from_http(
            403,
            &headers_with_reason("RISK_ACCEPTANCE_REQUIRED"),
            "needs explicit acceptance",
        );
        match err {
            CleanLibraryError::RiskAcceptanceRequired { docs_url, .. } => {
                assert!(docs_url.is_some());
            }
            other => panic!("expected RiskAcceptanceRequired, got {:?}", other),
        }
    }

    #[test]
    fn maps_429_with_retry_after() {
        let mut h = HeaderMap::new();
        h.insert("Retry-After", HeaderValue::from_static("42"));
        let err = from_http(429, &h, "throttled");
        match err {
            CleanLibraryError::RateLimitExceeded { retry_after_seconds, .. } => {
                assert_eq!(retry_after_seconds, 42);
            }
            other => panic!("expected RateLimitExceeded, got {:?}", other),
        }
        assert!(err.is_retryable());
    }

    #[test]
    fn maps_429_default_retry_after() {
        let err = from_http(429, &HeaderMap::new(), "");
        match err {
            CleanLibraryError::RateLimitExceeded { retry_after_seconds, .. } => {
                assert_eq!(retry_after_seconds, 60);
            }
            other => panic!("expected RateLimitExceeded, got {:?}", other),
        }
    }

    #[test]
    fn maps_404_to_package_not_found() {
        let err = from_http(404, &HeaderMap::new(), "not in catalog");
        assert!(matches!(err, CleanLibraryError::PackageNotFound(_)));
    }

    #[test]
    fn maps_500s_retryability() {
        for status in [500, 501, 505] {
            let err = from_http(status, &HeaderMap::new(), "");
            match err {
                CleanLibraryError::ServerError { retryable, .. } => assert!(!retryable),
                _ => panic!("expected ServerError"),
            }
        }
        for status in [502, 503, 504] {
            let err = from_http(status, &HeaderMap::new(), "");
            match err {
                CleanLibraryError::ServerError { retryable, .. } => assert!(retryable),
                _ => panic!("expected ServerError"),
            }
        }
    }

    #[test]
    fn integrity_failure_carries_reason() {
        let err = from_http(403, &headers_with_reason("INTEGRITY_FAILURE"), "hash mismatch");
        match err {
            CleanLibraryError::IntegrityFailure { reason_code, .. } => {
                assert_eq!(reason_code, "INTEGRITY_FAILURE");
            }
            _ => panic!("expected IntegrityFailure"),
        }
    }

    #[test]
    fn insufficient_data_carries_reason() {
        let err = from_http(
            403,
            &headers_with_reason("INSUFFICIENT_DATA_FAIL_CLOSED"),
            "no verdict",
        );
        assert!(matches!(err, CleanLibraryError::InsufficientData { .. }));
    }
}