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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! HTTP transport — `Client` wraps reqwest with auth header injection +
//! timeout + per Client spec rev1 §2 + Rev 2 amendment §2 + §4.
//!
//! Phase 1 substrate: `fetch_verdict` is the first transport consumer
//! (CLEANLIB-30); subsequent CLEANLIB-N PRs add `scan` / `audit` /
//! `policy preview` / `fetch` verb impls reusing this `Client`.

use std::time::Duration;

use reqwest::{header, Client as ReqwestClient, Method, Url};

use crate::attestation_verify::PinnedKeyMap;
use crate::config::Config;
use crate::errors::{from_http, CleanLibraryError, TransportError};
use crate::types::{
    AuditResponse, PolicyPreviewRequest, PolicyPreviewResponse, ScanRequest, ScanResponse, Verdict,
};

/// Default HTTP timeout per Rev 2 amendment §4.1 — allows 1-5s GCS-catalog
/// first-request-ingest + buffer.
const DEFAULT_TIMEOUT_SECS: u64 = 30;

/// `Client` is the cleanlib-client HTTP transport handle. Cheap to clone;
/// share across verbs in the same process.
#[derive(Debug, Clone)]
pub struct Client {
    http: ReqwestClient,
    base_url: Url,
    api_key: Option<String>,
    api_version: String,
}

/// Outcome of a remediation fetch (CLEANLIB-733 Rust remediation client).
/// Mirrors the sdk-py/js/go `RemediationOrAbsent` discriminated union: a 404 is
/// a distinct, cacheable "no data" answer — never collapsed into a transient.
#[derive(Debug, Clone)]
pub enum RemediationOutcome {
    /// `2xx` — the sparse remediation composite (loosely-typed JSON, matching
    /// the envelope `remediation` field shape).
    Present(serde_json::Value),
    /// `404 REMEDIATION_NOT_FOUND` — a true, final "no remediation data for this
    /// coordinate" answer, distinct from a transient failure.
    NotInSubstrate,
    /// `5xx` / transport — a transient failure; a retry may succeed.
    Transient(String),
}

/// Filters for [`Client::audit`] (CLEANLIB-813). All fields are optional —
/// `AuditFilters::default()` (or any `..Default::default()` spread)
/// queries the full audit log, matching the prior `audit(None, None,
/// None)` shape byte-for-byte.
///
/// Deliberately an options struct rather than positional parameters:
/// `until` is the filter this ticket adds (the real server already
/// accepts it — `cleanlib-app/src/verbs.rs` — and Go's SDK already
/// exposes it; this SDK never did). A 4th positional parameter would
/// have been ANOTHER breaking signature change on top of the one this
/// struct already is, and the same problem recurs at the 5th filter.
/// Every field here is purely additive from a caller's perspective when
/// built via `AuditFilters { since: Some(x), ..Default::default() }` —
/// a future filter lands as one new field, never another migration.
#[derive(Debug, Clone, Copy, Default)]
pub struct AuditFilters<'a> {
    /// Only entries at or after this RFC 3339 timestamp.
    pub since: Option<&'a str>,
    /// CLEANLIB-813: only entries at or before this RFC 3339 timestamp —
    /// bounds the END of the query window. The gap this ticket closes.
    pub until: Option<&'a str>,
    /// Only entries with this decision (`ALLOW` / `INSUFFICIENT` / `DENY`
    /// — see `cleanlib-cli`'s `VALID_DECISION_FILTERS` for the
    /// client-side-validated domain).
    pub decision: Option<&'a str>,
    /// Only entries for this ecosystem.
    pub ecosystem: Option<&'a str>,
}

impl Client {
    /// Construct from a loaded `Config`. TLS required for non-localhost
    /// endpoints. Returns `TlsRequired` for `http://` on remote hosts.
    pub fn from_config(config: &Config) -> Result<Self, CleanLibraryError> {
        Self::build(&config.endpoint.url, config.auth.api_key.clone(), &config.endpoint.api_version)
    }

    /// Construct with explicit endpoint + api_key. Intended for integration
    /// tests + ad-hoc invocations (e.g., CLI `--endpoint=` flag future).
    pub fn new(endpoint: &str, api_key: Option<String>) -> Result<Self, CleanLibraryError> {
        Self::build(endpoint, api_key, "v1")
    }

    fn build(
        endpoint: &str,
        api_key: Option<String>,
        api_version: &str,
    ) -> Result<Self, CleanLibraryError> {
        let base_url = Url::parse(endpoint)
            .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", endpoint, e)))?;

        let is_localhost = matches!(
            base_url.host_str(),
            Some("localhost") | Some("127.0.0.1") | Some("::1")
        );
        if base_url.scheme() != "https" && !is_localhost {
            return Err(TransportError::TlsRequired(endpoint.to_string()).into());
        }

        let http = ReqwestClient::builder()
            .timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
            .user_agent(concat!("cleanlib-cli/", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(TransportError::Network)?;

        Ok(Self {
            http,
            base_url,
            api_key,
            api_version: api_version.to_string(),
        })
    }

    /// Cosign gate 3 (Q6=a): verify a `Verdict`'s signed attestation.
    ///
    /// Q14 (capability parity, not policy) — this is opt-in. Nothing else in
    /// `Client` calls this; a caller that never invokes it sees no behavior
    /// change. Returns `Err(AttestationInvalid { reason_code:
    /// "ATTESTATION_ABSENT", .. })` when the verdict carries no attestation
    /// at all (distinct from a present-but-invalid one) so callers can tell
    /// "nothing to verify" apart from "verification failed".
    ///
    /// Post gate-3 redesign (2026-09-13, BD-ratified per Jira CLEANLIB-379
    /// comment 804236): verifies against [`PinnedKeyMap`] — a compiled-in,
    /// fail-closed key set — NOT a `/v1/pubkeys` fetch. See
    /// [`crate::attestation_verify`]'s module doc for why the earlier
    /// fetch-by-`key_id` design (PR #536) was architecturally circular and
    /// got redesigned before any release shipped it as a default. No lazy
    /// network object to build here anymore — `PinnedKeyMap::default()` is
    /// a cheap, synchronous, in-memory construction.
    pub async fn verify_attestation(&self, verdict: &Verdict) -> Result<(), CleanLibraryError> {
        let envelope = verdict.attestation.as_ref().ok_or_else(|| {
            CleanLibraryError::AttestationInvalid {
                reason_code: "ATTESTATION_ABSENT".to_string(),
                message: "verdict carries no attestation (attestation_status = \
                          signature_absent, or a v1/pre-attestation response)"
                    .to_string(),
            }
        })?;
        let lookup = PinnedKeyMap::default();
        crate::attestation_verify::verify_attestation(envelope, &lookup).await
    }

    /// Fetch a single verdict per App Rev 4 §9.3 +
    /// `GET /v1/customer/verdicts/{ecosystem}/{package}/{version}`.
    pub async fn fetch_verdict(
        &self,
        ecosystem: &str,
        package: &str,
        version: &str,
    ) -> Result<Verdict, CleanLibraryError> {
        let path = format!(
            "{}/customer/verdicts/{}/{}/{}",
            self.api_version,
            urlencode(ecosystem),
            urlencode(package),
            urlencode(version),
        );
        let url = self
            .base_url
            .join(&path)
            .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))?;

        let response = self.send(Method::GET, url).await?;
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.text().await.map_err(TransportError::Network)?;

        if !status.is_success() {
            return Err(from_http(status.as_u16(), &headers, &body));
        }

        serde_json::from_str(&body)
            .map_err(|e| CleanLibraryError::Parse(format!("verdict response: {}", e)))
    }

    /// Submit a packages + optional-policy request to
    /// `POST /v1/scan` — batch-resolve verdicts for a set of packages against
    /// the customer's active policy. Used by `cleanlib scan`. The App resolves
    /// each package independently (partial-success: a per-package miss lands as
    /// `ScanResult.error`, not a whole-batch failure), so the caller derives
    /// the gating decision per `ScanResult.verdict` and aggregates the exit
    /// code (`commands::scan`).
    ///
    /// Distinct endpoint from [`Self::policy_preview`]: `/v1/scan` needs no
    /// `policy_yaml`. Routing scan through `/v1/policy/preview` produced a
    /// `422 missing field policy_yaml`, and the old `PolicyPreviewResponse`
    /// (`{decisions}`, `#[serde(default)]`) silently parsed the App's
    /// `{results}` body into an empty vec → `scan_exit_code(&[]) == 0`, a
    /// fail-open on the security gate. Both are closed here.
    pub async fn scan(&self, req: &ScanRequest) -> Result<ScanResponse, CleanLibraryError> {
        let path = format!("{}/scan", self.api_version);
        let url = self
            .base_url
            .join(&path)
            .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))?;

        let body = serde_json::to_vec(req)
            .map_err(|e| CleanLibraryError::Parse(format!("scan body: {}", e)))?;

        let response = self
            .send_with_body(Method::POST, url, body, "application/json")
            .await?;
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.text().await.map_err(TransportError::Network)?;

        if !status.is_success() {
            return Err(from_http(status.as_u16(), &headers, &body));
        }

        let mut resp: ScanResponse = serde_json::from_str(&body)
            .map_err(|e| CleanLibraryError::Parse(format!("scan response: {}", e)))?;
        // CLEANLIB-480 · stamp the `x-request-id` from the response header onto
        // the parsed body so SDK callers can `resp.request_id` for correlation
        // debugging without a raw HTTP bypass.
        resp.request_id = extract_request_id(&headers);
        Ok(resp)
    }

    /// `POST /v1/policy/preview`. Used by `cleanlib policy preview` (with an
    /// explicit candidate policy override). NOTE: `cleanlib scan` uses
    /// [`Self::scan`] (`/v1/scan`), NOT this endpoint.
    ///
    /// CLEANLIB-305 DX-fix: corrected from `/v1/customer/policy/preview`
    /// (which 404s) to `/v1/policy/preview` (which the App mounts via
    /// `verbs_router`). Same class of bug as the cycle-14 `/v1/audit`
    /// fix (see `audit` below): the `/customer/` prefix is used only by
    /// `customer_verdicts_router` (`/v1/customer/verdicts/*`); the
    /// cycle-6 verb surface (`scan`, `audit`, `policy/preview`,
    /// `risk-accept`, `fetch/*`) mounts flat under `/v1`.
    pub async fn policy_preview(
        &self,
        req: &PolicyPreviewRequest,
    ) -> Result<PolicyPreviewResponse, CleanLibraryError> {
        let path = format!("{}/policy/preview", self.api_version);
        let url = self
            .base_url
            .join(&path)
            .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))?;

        let body = serde_json::to_vec(req)
            .map_err(|e| CleanLibraryError::Parse(format!("policy_preview body: {}", e)))?;

        let response = self.send_with_body(Method::POST, url, body, "application/json").await?;
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.text().await.map_err(TransportError::Network)?;

        if !status.is_success() {
            return Err(from_http(status.as_u16(), &headers, &body));
        }

        let mut resp: PolicyPreviewResponse = serde_json::from_str(&body)
            .map_err(|e| CleanLibraryError::Parse(format!("policy_preview response: {}", e)))?;
        // CLEANLIB-480 · stamp `x-request-id` from the response header.
        resp.request_id = extract_request_id(&headers);
        Ok(resp)
    }

    /// Fetch the raw artifact bytes for `(ecosystem, package, version)` via
    /// App's unified catalog-proxy `GET /v1/fetch/{ecosystem}/{package}/{version}`
    /// (CLEANLIB-302 / CLEANLIB-368). Returns owned `Vec<u8>` — caller decides
    /// write target. Emits decision + reason headers to stderr for visibility
    /// (binary stdout stays clean).
    ///
    /// **CLEANLIB-368 route pivot**: prior cycles built per-ecosystem registry
    /// paths (`/npm/<pkg>/-/<pkg>-<ver>.tgz`, `/go/<pkg>/@v/<ver>.zip`, …)
    /// against the App's cycle-3 §C.8 nested per-eco routers. Those paths are
    /// legacy registry-mimic shapes that never surfaced the CLEANLIB-302 audit
    /// row (`gcs_hit` / `gcs_object_path` / `bytes_served`) and hard-coded
    /// pypi wheel-variant assumptions that diverge from the real serve path.
    /// The App unifies both under `verbs_router` at `/v1/fetch/*` — that is
    /// now the sole client-side route.
    pub async fn fetch_artifact(
        &self,
        ecosystem: &str,
        package: &str,
        version: &str,
    ) -> Result<Vec<u8>, CleanLibraryError> {
        let url = build_fetch_url(&self.base_url, &self.api_version, ecosystem, package, version)?;
        let response = self.send(Method::GET, url).await?;
        let status = response.status();
        let headers = response.headers().clone();

        if !status.is_success() {
            let body = response.text().await.map_err(TransportError::Network)?;
            return Err(from_http(status.as_u16(), &headers, &body));
        }

        emit_decision_headers(&headers);

        let bytes = response.bytes().await.map_err(TransportError::Network)?;
        Ok(bytes.to_vec())
    }

    /// CLEANLIB-733 / step-4 Rust remediation client — fetch the sparse
    /// remediation composite via the cleanapp CUSTOMER-BOUNDARY FACADE
    /// (`GET /v1/customer/remediation/{eco}/{pkg}`, the same customer key that
    /// opens the verdict surface). Sister of the sdk-py / sdk-js / sdk-go
    /// `HttpRemediationClient`.
    ///
    /// Status mapping mirrors the other SDKs: `404` → [`RemediationOutcome::NotInSubstrate`]
    /// (a true, final "no remediation data" answer — never conflated with a
    /// transient, the [Degr≡Real] guard the facade 404-passthrough fix restored),
    /// `5xx`/transport → [`RemediationOutcome::Transient`], `2xx` →
    /// [`RemediationOutcome::Present`]. Internal/producer-bearer callers hit the
    /// direct enrich host — construct the `Client` with that endpoint and use
    /// [`Self::get_remediation_direct`]. Scoped npm packages (`@scope/name`) are
    /// percent-encoded to a single `%2F` segment (CLEANLIB-737 guard; see
    /// `urlencode`).
    pub async fn get_remediation(
        &self,
        ecosystem: &str,
        package: &str,
    ) -> Result<RemediationOutcome, CleanLibraryError> {
        self.remediation_with_mode(ecosystem, package, true).await
    }

    /// Direct-mode remediation for internal/producer-bearer callers: hits the
    /// pre-facade `GET /api/v1/remediation/{eco}/{pkg}` path on the configured
    /// (enrich-host) endpoint. Preserves the direct path per the un-park item-3.
    pub async fn get_remediation_direct(
        &self,
        ecosystem: &str,
        package: &str,
    ) -> Result<RemediationOutcome, CleanLibraryError> {
        self.remediation_with_mode(ecosystem, package, false).await
    }

    async fn remediation_with_mode(
        &self,
        ecosystem: &str,
        package: &str,
        facade: bool,
    ) -> Result<RemediationOutcome, CleanLibraryError> {
        let url = build_remediation_url(&self.base_url, &self.api_version, facade, ecosystem, package)?;
        let response = self.send(Method::GET, url).await?;
        let status = response.status();
        if status.as_u16() == 404 {
            return Ok(RemediationOutcome::NotInSubstrate);
        }
        if status.is_server_error() {
            return Ok(RemediationOutcome::Transient(format!("HTTP {}", status.as_u16())));
        }
        if !status.is_success() {
            let headers = response.headers().clone();
            let body = response.text().await.map_err(TransportError::Network)?;
            return Err(from_http(status.as_u16(), &headers, &body));
        }
        let body = response.text().await.map_err(TransportError::Network)?;
        let json: serde_json::Value =
            serde_json::from_str(&body).map_err(|e| CleanLibraryError::Parse(e.to_string()))?;
        Ok(RemediationOutcome::Present(json))
    }

    /// Streaming variant of [`Self::fetch_artifact`] — writes chunks to
    /// `writer` without buffering the full body in memory. Per Client Rev 2
    /// amendment §9.4 cycle-4 §D.5 streaming substrate. Returns total bytes
    /// written. Decision + reason headers surface to stderr before stream.
    /// Hits the same unified `/v1/fetch/{ecosystem}/{package}/{version}`
    /// proxy as [`Self::fetch_artifact`] — see the CLEANLIB-368 route pivot
    /// note there.
    pub async fn fetch_artifact_stream<W>(
        &self,
        ecosystem: &str,
        package: &str,
        version: &str,
        writer: &mut W,
    ) -> Result<u64, CleanLibraryError>
    where
        W: tokio::io::AsyncWrite + Unpin,
    {
        use futures_util::StreamExt;
        use tokio::io::AsyncWriteExt;

        let url = build_fetch_url(&self.base_url, &self.api_version, ecosystem, package, version)?;
        let response = self.send(Method::GET, url).await?;
        let status = response.status();
        let headers = response.headers().clone();

        if !status.is_success() {
            let body = response.text().await.map_err(TransportError::Network)?;
            return Err(from_http(status.as_u16(), &headers, &body));
        }

        emit_decision_headers(&headers);

        let mut total: u64 = 0;
        let mut stream = response.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let bytes = chunk.map_err(TransportError::Network)?;
            writer
                .write_all(&bytes)
                .await
                .map_err(|e| CleanLibraryError::Parse(format!("write artifact chunk: {}", e)))?;
            total += bytes.len() as u64;
        }
        writer
            .flush()
            .await
            .map_err(|e| CleanLibraryError::Parse(format!("flush artifact stream: {}", e)))?;
        Ok(total)
    }

    /// Query customer audit log via `GET /v1/audit` with optional filters.
    /// Caller passes already-validated filter values.
    ///
    /// Cycle-14 DX-fix: corrected from `/v1/customer/audit` (which 404s) to
    /// `/v1/audit` (which the App mounts via `verbs_router`). Verified live
    /// against cleanapp.clnstrt.dev 2026-06-05 — direct probe returns 200
    /// with `{window, records, backend_status}`.
    ///
    /// CLEANLIB-813: takes an [`AuditFilters`] options struct rather than
    /// positional `Option<&str>` params. The real server
    /// (`cleanlib-app/src/verbs.rs`) accepts a fourth filter, `until`, that
    /// this SDK never exposed — Go's SDK already supports it. Adding it as
    /// a 4th positional parameter would have been a breaking signature
    /// change today AND set up another one the next time a filter is
    /// added; an options struct absorbs `until` now and any future filter
    /// later as a purely additive field, so every existing
    /// `..Default::default()`-built call site keeps compiling. This IS a
    /// breaking change for existing positional callers (Rust has no
    /// source-compat path from 3 positional params to a struct) — the
    /// migration cost is paid once, here, rather than deferred to the next
    /// filter add.
    pub async fn audit(
        &self,
        filters: AuditFilters<'_>,
    ) -> Result<AuditResponse, CleanLibraryError> {
        let path = format!("{}/audit", self.api_version);
        let mut url = self
            .base_url
            .join(&path)
            .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))?;
        {
            let mut q = url.query_pairs_mut();
            if let Some(s) = filters.since {
                q.append_pair("since", s);
            }
            // CLEANLIB-813: the one genuinely new filter this ticket exists
            // for — bounds the END of the audit query's time window, mirroring
            // Go's SDK. `cleanlib-app/src/verbs.rs` already accepts it; only
            // this SDK's `audit()` never threaded it through.
            if let Some(u) = filters.until {
                q.append_pair("until", u);
            }
            if let Some(d) = filters.decision {
                q.append_pair("decision", d);
            }
            if let Some(e) = filters.ecosystem {
                q.append_pair("ecosystem", e);
            }
        }

        let response = self.send(Method::GET, url).await?;
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.text().await.map_err(TransportError::Network)?;

        if !status.is_success() {
            return Err(from_http(status.as_u16(), &headers, &body));
        }

        let mut resp: AuditResponse = serde_json::from_str(&body)
            .map_err(|e| CleanLibraryError::Parse(format!("audit response: {}", e)))?;
        // CLEANLIB-480 · stamp `x-request-id` from the response header — the
        // per-CALL identifier, distinct from `AuditEntry::request_id` (which
        // is the record-scoped per-row id persisted in the audit log).
        resp.request_id = extract_request_id(&headers);
        Ok(resp)
    }

        pub async fn probe_auth(&self) -> Result<(), CleanLibraryError> {
        let path = format!("{}/audit", self.api_version);
        let url = self
            .base_url
            .join(&path)
            .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))?;
        let response = self.send(Method::GET, url).await?;
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.text().await.map_err(TransportError::Network)?;
        if status.is_success() {
            return Ok(());
        }
        Err(from_http(status.as_u16(), &headers, &body))
    }

    /// Low-level: send a request with body + content-type + auth header.
    async fn send_with_body(
        &self,
        method: Method,
        url: Url,
        body: Vec<u8>,
        content_type: &str,
    ) -> Result<reqwest::Response, CleanLibraryError> {
        let mut req = self.http.request(method, url).body(body);
        req = req.header(header::CONTENT_TYPE, content_type);
        if let Some(key) = &self.api_key {
            req = req.header(header::AUTHORIZATION, format!("Bearer {}", key));
        }
        req.send().await.map_err(|e| {
            if e.is_timeout() {
                CleanLibraryError::Transport(TransportError::Timeout)
            } else {
                CleanLibraryError::Transport(TransportError::Network(e))
            }
        })
    }

    /// Low-level: send a request with auth header. Used internally by verb
    /// methods; public for advanced consumers (future).
    pub async fn send(
        &self,
        method: Method,
        url: Url,
    ) -> Result<reqwest::Response, CleanLibraryError> {
        let mut req = self.http.request(method, url);
        if let Some(key) = &self.api_key {
            req = req.header(header::AUTHORIZATION, format!("Bearer {}", key));
        }
        req.send().await.map_err(|e| {
            if e.is_timeout() {
                CleanLibraryError::Transport(TransportError::Timeout)
            } else {
                CleanLibraryError::Transport(TransportError::Network(e))
            }
        })
    }

    /// Expose the base URL for diagnostics + integration tests.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Fetch supported ecosystems from GET /health ecosystems_mounted field.
    pub async fn get_ecosystems(&self) -> Result<Vec<String>, CleanLibraryError> {
        let url = self.base_url.join("/health")
            .map_err(|e| CleanLibraryError::Transport(
                TransportError::InvalidUrl(e.to_string())
            ))?;
        let resp = self.http.get(url).send().await.map_err(|e| {
            CleanLibraryError::Transport(TransportError::Network(e))
        })?;
        let body_text = resp.text().await.map_err(|e| {
            CleanLibraryError::Transport(TransportError::Network(e))
        })?;
        let body: serde_json::Value = serde_json::from_str(&body_text)
            .map_err(|e| CleanLibraryError::Parse(e.to_string()))?;
        let ecosystems = body["ecosystems_mounted"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .filter_map(|v| v.as_str().map(|s| s.to_string()))
            .collect();
        Ok(ecosystems)
    }
}

/// CLEANLIB-480 · pull the `x-request-id` header off a response. Returns
/// `None` when the header is absent (older App builds pre-CLEANLIB-470) or
/// when the value is not UTF-8 (defence-in-depth — App always emits ASCII
/// ULIDs, so this is unreachable on a well-behaved server). HTTP header
/// names are case-insensitive so `x-request-id` matches `X-Request-Id`
/// either way. Free-standing so both the transport verbs and the tests
/// can share it.
pub(crate) fn extract_request_id(
    headers: &reqwest::header::HeaderMap,
) -> Option<String> {
    headers
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
}

/// Emit App's verdict + reason headers (when present) to stderr. Keeps
/// stdout clean for binary content + scripted consumers; visible to TTY
/// users for verdict awareness.
fn emit_decision_headers(headers: &reqwest::header::HeaderMap) {
    if let Some(decision) = headers
        .get("X-CleanLibrary-Decision")
        .and_then(|v| v.to_str().ok())
    {
        eprintln!("# decision: {}", decision);
    }
    if let Some(reason) = headers
        .get("X-CleanLibrary-Reason")
        .and_then(|v| v.to_str().ok())
    {
        eprintln!("# reason: {}", reason);
    }
}

/// Build the App-side catalog-proxy URL for a triple. Post-CLEANLIB-368 this
/// is the ONLY fetch URL shape the client emits: `GET /{api_version}/fetch/
/// {ecosystem}/{package}/{version}` — the unified verb the App mounts in
/// `verbs_router` (see `cleanlib-app/src/verbs.rs`), which returns
/// `application/octet-stream` on catalog-hit and a structured JSON 404 on
/// miss. Per CLEANLIB-302 this is the surface that emits the fetch-audit
/// `AuditRow` with `gcs_hit` / `gcs_object_path` / `bytes_served`
/// populated from the real catalog outcome — the substrate the
/// `/v1/audit` cache-hit-ratio metric consumes.
///
/// Every triple component is percent-encoded so path-embedded slashes
/// (npm-scoped `@scope/name`, go-module `github.com/…/…`) survive the
/// App's axum `Path<(String, String, String)>` extractor as a single
/// segment each.
fn build_fetch_url(
    base: &Url,
    api_version: &str,
    ecosystem: &str,
    package: &str,
    version: &str,
) -> Result<Url, TransportError> {
    let path = format!(
        "{}/fetch/{}/{}/{}",
        api_version,
        urlencode(ecosystem),
        urlencode(package),
        urlencode(version),
    );
    base.join(&path)
        .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))
}

/// Build the remediation URL. `facade` (customer) → `{api_version}/customer/
/// remediation/{eco}/{pkg}` on the cleanapp base; `!facade` (internal) → the
/// pre-facade `api/{api_version}/remediation/{eco}/{pkg}` direct path. Segments
/// go through `urlencode`, so a scoped npm package (`@scope/name`) becomes a
/// single `%2F`-encoded segment (CLEANLIB-737 guard) rather than a split path.
fn build_remediation_url(
    base: &Url,
    api_version: &str,
    facade: bool,
    ecosystem: &str,
    package: &str,
) -> Result<Url, TransportError> {
    let path = if facade {
        format!(
            "{}/customer/remediation/{}/{}",
            api_version,
            urlencode(ecosystem),
            urlencode(package),
        )
    } else {
        format!(
            "api/{}/remediation/{}/{}",
            api_version,
            urlencode(ecosystem),
            urlencode(package),
        )
    };
    base.join(&path)
        .map_err(|e| TransportError::InvalidUrl(format!("{}: {}", path, e)))
}

/// URL-encode a path segment. Covers `@` + `/` + reserved chars + unicode.
/// Avoids pulling the full `url` crate as a separate dep (re-export is via
/// `reqwest::Url`).
fn urlencode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => out.push(c),
            _ => {
                let mut buf = [0u8; 4];
                let encoded = c.encode_utf8(&mut buf);
                for b in encoded.bytes() {
                    out.push_str(&format!("%{:02X}", b));
                }
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Config, EndpointConfig};

    fn cfg(url: &str) -> Config {
        let mut c = Config::default();
        c.endpoint = EndpointConfig {
            url: url.to_string(),
            api_version: "v1".to_string(),
        };
        c
    }

    #[test]
    fn refuses_remote_plaintext() {
        let err = Client::from_config(&cfg("http://cleanapp.clnstrt.dev")).unwrap_err();
        assert!(matches!(
            err,
            CleanLibraryError::Transport(TransportError::TlsRequired(_))
        ));
    }

    #[test]
    fn allows_localhost_plaintext_for_testing() {
        let client = Client::new("http://localhost:8080", None).unwrap();
        assert_eq!(client.base_url().host_str(), Some("localhost"));
    }

    #[test]
    fn allows_127_loopback_plaintext() {
        let client = Client::new("http://127.0.0.1:8080", None).unwrap();
        assert_eq!(client.base_url().host_str(), Some("127.0.0.1"));
    }

    #[test]
    fn accepts_https_endpoint() {
        let client = Client::from_config(&cfg("https://cleanapp.clnstrt.dev")).unwrap();
        assert_eq!(client.base_url().as_str(), "https://cleanapp.clnstrt.dev/");
    }

    #[test]
    fn rejects_invalid_url() {
        let err = Client::from_config(&cfg("not a url")).unwrap_err();
        assert!(matches!(
            err,
            CleanLibraryError::Transport(TransportError::InvalidUrl(_))
        ));
    }

    #[test]
    fn urlencode_npm_scoped_pkg() {
        // @scope/pkg → %40scope%2Fpkg for safe URL embedding
        assert_eq!(urlencode("@my-org/foo"), "%40my-org%2Ffoo");
    }

    // ─── CLEANLIB-733 Rust remediation client (step 4) ──────────────────────
    #[test]
    fn remediation_url_facade_is_customer_path() {
        let base = Url::parse("https://cleanapp.clnstrt.dev").unwrap();
        let u = build_remediation_url(&base, "v1", true, "npm", "cors").unwrap();
        assert_eq!(u.path(), "/v1/customer/remediation/npm/cors");
    }

    #[test]
    fn remediation_url_direct_is_api_v1_path() {
        // Internal/producer-bearer mode preserves the pre-facade path (item-3).
        let base = Url::parse("https://cleanlib-enrich.clnstrt.dev").unwrap();
        let u = build_remediation_url(&base, "v1", false, "npm", "cors").unwrap();
        assert_eq!(u.path(), "/api/v1/remediation/npm/cors");
    }

    #[test]
    fn remediation_url_scoped_package_slash_is_percent_encoded() {
        // CLEANLIB-737 guard: a scoped npm package reaches the wire as a SINGLE
        // %2F-encoded segment, never a bare "/" that would split into an extra
        // segment and bind the wrong upstream coordinate.
        let base = Url::parse("https://cleanapp.clnstrt.dev").unwrap();
        let u = build_remediation_url(&base, "v1", true, "npm", "@babel/core").unwrap();
        assert!(u.as_str().contains("%2F"), "scope slash not encoded: {u}");
        assert!(
            u.as_str().ends_with("/npm/%40babel%2Fcore"),
            "want a single %2F-encoded scoped segment, got {u}"
        );
    }

    #[test]
    fn urlencode_passes_simple() {
        assert_eq!(urlencode("lodash"), "lodash");
        assert_eq!(urlencode("4.17.21"), "4.17.21");
        assert_eq!(urlencode("github.com/sirupsen/logrus"), "github.com%2Fsirupsen%2Flogrus");
    }

    #[test]
    fn urlencode_maven_coordinate_encodes_colon() {
        // CLEANLIB S3 / A3 Maven contract: maven package = groupId:artifactId;
        // the colon must percent-encode to %3A so the wire coordinate is
        // byte-identical across all 4 SDKs (sdk-go escapePathSeg / js
        // encodeURIComponent / py quote(safe='')). The allowlist urlencode
        // already does this — this test locks it against regression.
        assert_eq!(
            urlencode("org.springframework:spring-beans"),
            "org.springframework%3Aspring-beans"
        );
        assert_eq!(
            urlencode("org.apache.logging.log4j:log4j-core"),
            "org.apache.logging.log4j%3Alog4j-core"
        );
    }

    #[test]
    fn urlencode_handles_unicode() {
        // UTF-8 multi-byte chars get percent-encoded byte-by-byte
        assert_eq!(urlencode("é"), "%C3%A9");
    }

    fn base() -> Url {
        Url::parse("https://cleanapp.clnstrt.dev").unwrap()
    }

    // CLEANLIB-368 route pivot: every ecosystem now resolves to the App's
    // unified `/{api_version}/fetch/{ecosystem}/{package}/{version}` catalog
    // proxy. The client no longer emits registry-mimic per-ecosystem paths
    // (`/npm/…/-/….tgz`, `/go/…/@v/….zip`, `/pypi/…/…-….tar.gz`) — those
    // URL-shape assertions are retired because they are the pre-pivot bug.
    #[test]
    fn fetch_url_routes_through_app_v1_fetch_for_npm_bare() {
        let url = build_fetch_url(&base(), "v1", "npm", "lodash", "4.17.21").unwrap();
        assert_eq!(
            url.as_str(),
            "https://cleanapp.clnstrt.dev/v1/fetch/npm/lodash/4.17.21"
        );
    }

    #[test]
    fn fetch_url_npm_scoped_encodes_at_and_slash() {
        // `@my-org/foo` must survive the App's Path extractor as a single
        // `{package}` segment — so `@` → `%40` and `/` → `%2F`.
        let url = build_fetch_url(&base(), "v1", "npm", "@my-org/foo", "1.0.0").unwrap();
        assert_eq!(
            url.as_str(),
            "https://cleanapp.clnstrt.dev/v1/fetch/npm/%40my-org%2Ffoo/1.0.0"
        );
    }

    #[test]
    fn fetch_url_go_module_path_slashes_encoded() {
        // `github.com/sirupsen/logrus` is one package identifier; its
        // internal `/`s must not split into extra path segments.
        let url = build_fetch_url(&base(), "v1", "go", "github.com/sirupsen/logrus", "v1.9.0")
            .unwrap();
        assert_eq!(
            url.as_str(),
            "https://cleanapp.clnstrt.dev/v1/fetch/go/github.com%2Fsirupsen%2Flogrus/v1.9.0"
        );
    }

    #[test]
    fn fetch_url_pypi_routes_through_v1_fetch_not_registry_mimic() {
        let url = build_fetch_url(&base(), "v1", "pypi", "requests", "2.31.0").unwrap();
        assert_eq!(
            url.as_str(),
            "https://cleanapp.clnstrt.dev/v1/fetch/pypi/requests/2.31.0"
        );
        // Explicitly assert the legacy pypi shape is NOT emitted.
        assert!(!url.as_str().contains("/pypi/requests/requests-"));
    }

    #[test]
    fn fetch_url_ecosystem_client_side_unopinionated() {
        // Post-pivot the client no longer rejects any ecosystem name; the
        // App owns catalog-lookup + returns a structured 404 on miss. This
        // closes the CLEANLIB-368 gap that had maven/crates/nuget/rubygems
        // failing at the client with `Phase 1 Tier A` before even hitting
        // the wire.
        for eco in ["maven", "crates", "nuget", "rubygems", "composer"] {
            let url = build_fetch_url(&base(), "v1", eco, "somepkg", "1.0.0").unwrap();
            assert_eq!(
                url.as_str(),
                format!("https://cleanapp.clnstrt.dev/v1/fetch/{}/somepkg/1.0.0", eco)
            );
        }
    }

    #[test]
    fn fetch_url_maven_coordinates_group_id_encoded() {
        // Maven coordinates use `group:artifact` (no `/`), but the `:` is a
        // reserved char in URL segments — urlencode covers it.
        let url = build_fetch_url(&base(), "v1", "maven", "junit:junit", "4.13.2").unwrap();
        assert_eq!(
            url.as_str(),
            "https://cleanapp.clnstrt.dev/v1/fetch/maven/junit%3Ajunit/4.13.2"
        );
    }

    #[test]
    fn fetch_url_honors_configured_api_version() {
        // Future-proof: if the config carries `api_version = "v2"`, the
        // client picks it up — no hard-coded `v1` in transport.
        let url = build_fetch_url(&base(), "v2", "npm", "lodash", "4.17.21").unwrap();
        assert_eq!(
            url.as_str(),
            "https://cleanapp.clnstrt.dev/v2/fetch/npm/lodash/4.17.21"
        );
    }

    // ── CLEANLIB-480 · x-request-id header extraction ────────────────────

    fn header_map(pairs: &[(&str, &str)]) -> reqwest::header::HeaderMap {
        let mut m = reqwest::header::HeaderMap::new();
        for (k, v) in pairs {
            m.insert(
                reqwest::header::HeaderName::from_bytes(k.as_bytes()).unwrap(),
                reqwest::header::HeaderValue::from_str(v).unwrap(),
            );
        }
        m
    }

    #[test]
    fn cleanlib_480_extract_request_id_reads_lowercase_header() {
        // App emit is lowercase per CLEANLIB-470 wire; extract must match.
        let h = header_map(&[("x-request-id", "01M1KWQ41SPRAP551FGW5ZN4RF")]);
        assert_eq!(
            extract_request_id(&h).as_deref(),
            Some("01M1KWQ41SPRAP551FGW5ZN4RF")
        );
    }

    #[test]
    fn cleanlib_480_extract_request_id_reads_mixed_case_header() {
        // HTTP header names are case-insensitive per RFC; the client must
        // read `X-Request-Id` identically to `x-request-id` so a future App
        // header casing change doesn't silently drop the id.
        let h = header_map(&[("X-Request-Id", "01ABC")]);
        assert_eq!(extract_request_id(&h).as_deref(), Some("01ABC"));
    }

    #[test]
    fn cleanlib_480_extract_request_id_absent_returns_none() {
        // Older App builds pre-CLEANLIB-470 emit no header — SDK callers
        // see `None`, not an error.
        let h = header_map(&[("content-type", "application/json")]);
        assert!(extract_request_id(&h).is_none());
    }

    #[test]
    fn cleanlib_480_extract_request_id_non_utf8_value_returns_none() {
        // Defence-in-depth: a non-UTF-8 header value (never emitted by the
        // App, but a proxy could inject one) must not panic or corrupt the
        // returned Option — the client returns None and the SDK caller
        // falls back to a null request_id.
        let mut h = reqwest::header::HeaderMap::new();
        h.insert(
            reqwest::header::HeaderName::from_static("x-request-id"),
            reqwest::header::HeaderValue::from_bytes(&[0x80, 0xFF]).unwrap(),
        );
        assert!(extract_request_id(&h).is_none());
    }
}