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
//! Cosign migration gate 3 (Q6=a, CLEANLIB-379 overnight arc) — Rust
//! reference implementation of SDK-side attestation signature verification.
//!
//! Q14 (capability parity, not policy): this module exposes a capability —
//! `verify_attestation()` — that an integrator calls when THEY decide a
//! signature check matters. Nothing in `cleanlib-client` invokes this
//! automatically on the normal verdict-fetch path; a caller that never calls
//! it pays zero cost and sees identical behavior to before this module
//! existed. Matches the CLI/MCP-tool posture (no forced default).
//!
//! # Design history — why the trust root is a compiled-in map, not a fetch
//!
//! The FIRST cut of this module (PR #536, merged `acab7f44fd8d`) shipped
//! [`PubkeysEndpointLookup`] as the DEFAULT [`AttestationKeyLookup`]: it
//! resolved an attestation's `key_id` by fetching `GET /v1/pubkeys` from
//! `cleanlib-app` — the SAME service whose signatures it was verifying.
//! BD/PM-seat review (2026-09-13, ratified via Jira CLEANLIB-379 comment
//! 804236) found this architecturally circular and directed a redesign:
//!
//! - `key_id` lives on `SignedAttestation` (the wire envelope), NOT inside
//!   `Attestation` (the struct `cleanlib-cosign-signer` actually signs via
//!   JCS `canonical_bytes()`) — confirmed by reading
//!   `cleanlib-cosign-signer/src/lib.rs` lines 91–140. `key_id` is UNSIGNED.
//! - A verifier that uses that unsigned field to pick which key to trust,
//!   fetched from the same service producing the signature, gives no
//!   protection against a compromised/malicious service: whoever controls
//!   `/v1/pubkeys` controls what "verifies." This made the business claim
//!   ("checked... without trusting us and without our service being up")
//!   false under the PR #536 shape.
//!
//! **Ratified shape (this module, post-redesign):**
//! 1. [`PinnedKeyMap`] — a COMPILED-IN `key_id -> PEM` map for every key ever
//!    signed with (today: staging + prod), shipped in the SDK binary, not
//!    fetched at runtime. This is the new DEFAULT trust root.
//! 2. Unknown `key_id` FAILS CLOSED — [`PinnedKeyMap::lookup_pem`] never
//!    makes a network call; an unrecognized `key_id` is an immediate,
//!    permanent `AttestationInvalid`, never a fetch-and-hope.
//! 3. [`PubkeysEndpointLookup`] is DEMOTED to a convenience-only helper (see
//!    its doc comment) — it must never be wired as the default
//!    `AttestationKeyLookup` for `verify_attestation`/`Client::verify_attestation`
//!    again. Its role now is exactly [`PubkeysEndpointLookup::describe_unknown_key`]:
//!    producing HUMAN-READABLE advisory text ("unknown key_id, verify its
//!    fingerprint out of band") — it must never feed a trust decision.
//! 4. Publishing fingerprints somewhere independent of the service (so an
//!    operator has something to check `describe_unknown_key`'s advisory
//!    against) is a process/docs follow-up, tracked separately — not a code
//!    change in this module.
//!
//! Verification recipe (unchanged by the redesign — only key RESOLUTION
//! changed, not the verify math). Reproduces `cleanlib-cosign-signer`'s
//! `partner_guide_7_2_method_verifies_signer_signature` test from the
//! CONSUMER side, independently — this crate does NOT and must NOT depend on
//! `cleanlib-cosign-signer`, which is `publish = false` / service-internal
//! per `PUBLISHING.md` §1.2):
//! 1. Parse the wire envelope `{attestation: {...}, signature_b64, key_id}`
//!    (the exact shape `Verdict::attestation` carries as a passthrough
//!    `serde_json::Value` — see `types.rs` CLEANLIB-496 doc comment).
//! 2. Re-serialize the `attestation` sub-object using RFC-8785 JCS
//!    (`serde_jcs`) — this is what the signer actually signs
//!    (`Attestation::canonical_bytes()`), REGARDLESS of the wire's incidental
//!    key order/whitespace. A natural parse + JCS-reserialize is
//!    byte-identical to the signer's bytes; no hand-replicated field order.
//! 3. base64-decode `signature_b64`, DER-decode as a P-256 ECDSA signature.
//! 4. Resolve `key_id` to a PEM via the caller-supplied [`AttestationKeyLookup`]
//!    (the default [`PinnedKeyMap`] — compiled-in, fail-closed, no network),
//!    parse the PEM as a `VerifyingKey`.
//! 5. `verifying_key.verify(canonical_bytes, &signature)`.
//!
//! Errors route through the EXISTING `CleanLibraryError` taxonomy rather than
//! a bespoke type: malformed envelopes and signature/key/canonical-form
//! mismatches are `AttestationInvalid` (a variant CLEANLIB-657 already
//! reserved for exactly this "signed attestation present but failed
//! verification" case); a transient key-lookup failure (network/5xx while
//! fetching `/v1/pubkeys` via the now convenience-only
//! [`PubkeysEndpointLookup`]) is the existing `Transport` variant, so callers
//! already branching on `CleanLibraryError::is_retryable()` get the right
//! answer for free.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use ecdsa::signature::Verifier;
use p256::ecdsa::{Signature, VerifyingKey};
use p256::pkcs8::DecodePublicKey;
use reqwest::{Client as ReqwestClient, Url};
use tokio::sync::RwLock;

use crate::errors::{CleanLibraryError, TransportError};

/// Default TTL for a cached `key_id -> PEM` entry (charter default: 1h). KMS
/// key-version MATERIAL is immutable once created (only `state` changes), so
/// this TTL exists to notice a NEW key-version being added to `/v1/pubkeys`
/// (e.g. ahead of gate 5 cutover), not to detect rotation-in-place — there is
/// no rotation-in-place for a given key_id.
pub const DEFAULT_PUBKEY_CACHE_TTL: Duration = Duration::from_secs(3600);

/// Resolves an attestation's `key_id` to a PEM-encoded P-256 public key.
///
/// Exists as a trait (rather than hardcoding the HTTP fetch inside
/// `verify_attestation`) so:
/// - tests / air-gapped verification can substitute a static in-memory
///   lookup (see `tests` module below) without a network dependency, and
/// - a future consumer with a different trust distribution mechanism (e.g. a
///   pre-provisioned key bundle) can implement this trait instead of the
///   default HTTP one, without `verify_attestation` itself changing.
#[async_trait]
pub trait AttestationKeyLookup: Send + Sync {
    /// Resolve `key_id` (the exact string carried on `SignedAttestation.key_id`
    /// — the full KMS key-version resource path, e.g.
    /// `projects/.../cryptoKeys/cleanlib-cosign-staging/cryptoKeyVersions/1`)
    /// to a PEM-encoded SubjectPublicKeyInfo. Implementations should treat a
    /// "no such key_id" answer as `AttestationInvalid` (permanent — retrying
    /// the same key_id against the same catalog will not help) and a
    /// network/5xx failure as `Transport` (transient — retry may succeed).
    async fn lookup_pem(&self, key_id: &str) -> Result<String, CleanLibraryError>;
}

/// Staging KMS key_id/PEM, mirrored VERBATIM from `cleanlib-app`'s
/// `/v1/pubkeys` handler (`cleanlib-app/src/http.rs::pubkeys()`,
/// `STAGING_KEY_ID`/`STAGING_PEM` constants — point-in-time
/// `gcloud kms keys versions get-public-key` fetch, 2026-09-11, keyring
/// `cleanlibrary-signing`, project `cleanlibrary-prod`). This is the
/// ACTIVE signing key as of that fetch — every attestation issued in
/// production today carries this `key_id`.
///
/// KMS key-version key MATERIAL is immutable once created (only `state`
/// changes) — this mirror only goes stale when a genuinely NEW key version
/// is minted, which per the App-side doc comment is "a BD-direct,
/// coordinated rotation event," not something either side auto-detects.
/// **A new key version requires a coordinated SDK release updating this
/// map** — that coupling is the intended fail-closed behavior, not a defect.
const STAGING_KEY_ID: &str = "projects/cleanlibrary-prod/locations/us-central1/keyRings/cleanlibrary-signing/cryptoKeys/cleanlib-cosign-staging/cryptoKeyVersions/1";
const STAGING_PEM: &str = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE1yxckriMfZCZHgbnedOO6RHxg+Hq\nV6gRTA5/wIZtTbBLmVSg5//9L6xLvD7CaLEUMg8aH3+8vuytxl4K2wB7uA==\n-----END PUBLIC KEY-----\n";

/// Prod KMS key_id/PEM. **Key MATERIAL mirrored from the same `pubkeys()`
/// handler** (`PROD_KEY_ID`/`PROD_PEM`), but re-line-wrapped here — the
/// App-side constant's base64 body is emitted as one 124-char line with no
/// RFC 7468 64-char wrap. Python's lenient `base64.b64decode` accepts that
/// (91 bytes, correct P-256 SPKI length either way), but Rust's
/// `p256::pkcs8::DecodePublicKey` — and any other strict PEM parser — does
/// not: `pinned_key_map_builtin_entries_are_well_formed` below caught this by
/// literally trying to parse the App's own constant. Same key bytes, just
/// correctly wrapped; **the underlying `/v1/pubkeys` defect in
/// `cleanlib-app/src/http.rs` still needs an App-lane fix** so every OTHER
/// strict-PEM consumer of that endpoint (not just this SDK) isn't affected —
/// flagged separately, not silently worked around by mirroring the bug here.
///
/// Provisioned + ENABLED, not yet the active signer (cutover is cosign gate
/// 5, BD-direct) — pinned here now so an SDK built today already recognizes
/// it the moment gate 5 flips, with no SDK re-release required for that
/// specific transition.
const PROD_KEY_ID: &str = "projects/cleanlibrary-prod/locations/us-central1/keyRings/cleanlibrary-signing/cryptoKeys/cleanlib-cosign-prod/cryptoKeyVersions/1";
const PROD_PEM: &str = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoHzMRp8uj6k8tv4YXpI8r/5eC3sC\nwoKhnouHz83WkAWGMd2U30R4Wpr6JR1WfI+MH6/Q6o4T8cAnYee91oa98g==\n-----END PUBLIC KEY-----\n";

/// The DEFAULT [`AttestationKeyLookup`] as of the gate-3 redesign
/// (2026-09-13, BD-ratified per Jira CLEANLIB-379 comment 804236 —
/// see the module-level "Design history" doc above).
///
/// A compiled-in `key_id -> PEM` map. **No network capability exists on this
/// type at all** — there is no HTTP client field, no URL, nothing to fetch.
/// [`Self::lookup_pem`] is a pure in-memory match; an unrecognized `key_id`
/// returns `Err(AttestationInvalid)` immediately, which is what makes this
/// shape fail-closed rather than fail-open-via-fetch. This is deliberate:
/// the whole point of the redesign is that a verifier's trust root cannot be
/// steered by an unsigned wire field talking to the same service being
/// verified.
#[derive(Debug, Clone, Default)]
pub struct PinnedKeyMap {
    /// Additional out-of-band-verified keys a caller has independently
    /// confirmed (e.g. against a fingerprint published somewhere
    /// independent of `cleanlib-app`, per the redesign's point 4) — merged
    /// with the two built-in entries. Empty by default.
    extra: HashMap<String, String>,
}

impl PinnedKeyMap {
    /// The built-in set: today's staging + prod keys, exactly as
    /// `/v1/pubkeys` reports them at the time of this SDK release.
    pub fn new() -> Self {
        Self::default()
    }

    /// Pin an ADDITIONAL key the caller has verified out-of-band (e.g. a
    /// customer-specific signing key, or a new key_id whose fingerprint they
    /// checked against an independent publication per the redesign's point
    /// 4). Does not touch the network — the caller supplies the PEM
    /// directly; this method only extends the in-memory map.
    pub fn with_extra_key(mut self, key_id: impl Into<String>, pem: impl Into<String>) -> Self {
        self.extra.insert(key_id.into(), pem.into());
        self
    }

    /// The built-in (non-`extra`) entries, for tests/diagnostics — proves
    /// the compiled-in set actually contains today's known key_ids without
    /// exposing a way to mutate them.
    fn builtin() -> [(&'static str, &'static str); 2] {
        [(STAGING_KEY_ID, STAGING_PEM), (PROD_KEY_ID, PROD_PEM)]
    }
}

#[async_trait]
impl AttestationKeyLookup for PinnedKeyMap {
    async fn lookup_pem(&self, key_id: &str) -> Result<String, CleanLibraryError> {
        // Pure in-memory match — no `.await` point that could ever touch a
        // network driver. Checked first against `extra` (caller's own
        // out-of-band-verified pins take precedence) then the built-in set.
        if let Some(pem) = self.extra.get(key_id) {
            return Ok(pem.clone());
        }
        for (id, pem) in Self::builtin() {
            if id == key_id {
                return Ok(pem.to_string());
            }
        }
        // FAIL CLOSED: unrecognized key_id is a permanent, immediate error —
        // never a fetch-and-hope. This is the core safety property the
        // redesign exists to guarantee; see
        // `pinned_key_map_unknown_key_fails_closed_with_no_io_driver` below
        // for the structural (not just behavioral) proof.
        Err(CleanLibraryError::AttestationInvalid {
            reason_code: "ATTESTATION_KEY_ID_UNKNOWN".to_string(),
            message: format!(
                "key_id {key_id:?} is not in this SDK's pinned key set (staging + \
                 prod, plus any caller-supplied `with_extra_key` pins). This is a \
                 PERMANENT fail-closed result, not a transient fetch failure — this \
                 type never fetches. If you believe this key_id is legitimate (e.g. \
                 a new key version), verify its fingerprint out of band and either \
                 pin it via `PinnedKeyMap::with_extra_key` or wait for an SDK release \
                 that pins it by default. `PubkeysEndpointLookup::describe_unknown_key` \
                 can surface a human-readable hint, but must never be auto-trusted."
            ),
        })
    }
}

#[derive(Debug, Clone, serde::Deserialize)]
struct PubkeyEntry {
    key_id: String,
    pubkey_pem: String,
    algorithm: Option<String>,
}

#[derive(Debug, Clone, serde::Deserialize)]
struct PubkeysResponse {
    keys: Vec<PubkeyEntry>,
}

/// **DEMOTED to convenience-only as of the gate-3 redesign (2026-09-13) — do
/// NOT wire this as the default [`AttestationKeyLookup`] for
/// `verify_attestation`/`Client::verify_attestation`.** [`PinnedKeyMap`] is
/// the default now. See the module-level "Design history" doc for why:
/// fetching a verification key from the same service whose signature is
/// being verified is architecturally circular — whoever controls
/// `/v1/pubkeys` would control what "verifies."
///
/// This type still fetches `{base_url}/v1/pubkeys` (the endpoint
/// `cleanlib-app` publishes per cosign migration gate 1) and caches each
/// `key_id -> PEM` pair for `ttl`, unauthenticated + `no-store` (same
/// posture as `/health`). Its ONLY sanctioned use post-redesign is
/// [`Self::describe_unknown_key`] — producing a human-readable advisory a
/// caller can show a user when [`PinnedKeyMap`] doesn't recognize a
/// `key_id`, so they can go verify a fingerprint out of band. It must never
/// feed a `verify_attestation` trust decision directly; `AttestationKeyLookup::lookup_pem`
/// stays implemented here (so this type remains directly testable / usable
/// standalone, e.g. by a caller building their own advisory UX), but
/// `verify_attestation`'s DEFAULT path never reaches it.
#[derive(Debug, Clone)]
pub struct PubkeysEndpointLookup {
    http: ReqwestClient,
    pubkeys_url: Url,
    ttl: Duration,
    cache: Arc<RwLock<PubkeyCache>>,
}

/// `key_id -> (pem, algorithm, fetched_at)`. `algorithm` is carried alongside
/// the PEM purely so [`PubkeysEndpointLookup::describe_unknown_key`] can
/// quote it in its advisory text; the verify path never reads it.
type PubkeyCache = HashMap<String, (String, Option<String>, Instant)>;

impl PubkeysEndpointLookup {
    /// `base_url` is the App origin (e.g. `https://cleanapp.clnstrt.dev`);
    /// this joins `/v1/pubkeys` per the gate-1 endpoint. Uses
    /// [`DEFAULT_PUBKEY_CACHE_TTL`]; see [`Self::with_ttl`] to override.
    pub fn new(base_url: &Url) -> Result<Self, CleanLibraryError> {
        let pubkeys_url = base_url
            .join("/v1/pubkeys")
            .map_err(|e| TransportError::InvalidUrl(format!("/v1/pubkeys: {e}")))?;
        let http = ReqwestClient::builder()
            .timeout(Duration::from_secs(30))
            .user_agent(concat!("cleanlib-client/", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(TransportError::Network)?;
        Ok(Self {
            http,
            pubkeys_url,
            ttl: DEFAULT_PUBKEY_CACHE_TTL,
            cache: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    pub fn with_ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self
    }

    async fn fetch_and_cache_all(&self) -> Result<(), CleanLibraryError> {
        let response = self
            .http
            .get(self.pubkeys_url.clone())
            .send()
            .await
            .map_err(TransportError::Network)?;
        let status = response.status();
        if !status.is_success() {
            // Producer-side outage/5xx fetching the KEY CATALOG is a
            // transport-layer problem, not a verdict about any specific
            // key_id — surface as retryable Transport per the existing
            // `is_retryable()` contract (502/503/504 style reasoning).
            return Err(TransportError::Network(
                response.error_for_status().unwrap_err(),
            )
            .into());
        }
        // This crate's reqwest is built with `default-features = false` (no
        // `json` feature, matching every other call site in `transport.rs`
        // — see `Client::get_ecosystems`), so parse via `.text()` +
        // `serde_json::from_str` rather than pulling in a new reqwest
        // feature for this one call.
        let text = response.text().await.map_err(TransportError::Network)?;
        let body: PubkeysResponse = serde_json::from_str(&text)
            .map_err(|e| CleanLibraryError::Parse(format!("/v1/pubkeys response: {e}")))?;
        let now = Instant::now();
        let mut cache = self.cache.write().await;
        for entry in body.keys {
            cache.insert(entry.key_id, (entry.pubkey_pem, entry.algorithm, now));
        }
        Ok(())
    }

    /// Convenience-only advisory (see the type doc): when [`PinnedKeyMap`]
    /// doesn't recognize a `key_id`, a caller MAY use this to look up whether
    /// `/v1/pubkeys` reports that key_id anyway, and produce a human-readable
    /// hint — "this key_id exists on the server, go verify its fingerprint
    /// out of band before deciding whether to pin it." This NEVER returns a
    /// verified/trusted signal and must NEVER be fed into a trust decision —
    /// it only ever produces advisory text (`Option<String>`), never a PEM,
    /// never a bool, precisely so it cannot be mistaken for a verify result.
    ///
    /// Returns `None` if the server is unreachable or doesn't recognize the
    /// key_id either — absence of an advisory is not itself a security
    /// signal in either direction.
    pub async fn describe_unknown_key(&self, key_id: &str) -> Option<String> {
        if self.fetch_and_cache_all().await.is_err() {
            return None;
        }
        let cache = self.cache.read().await;
        let (_, algorithm, _) = cache.get(key_id)?;
        Some(format!(
            "key_id {key_id:?} IS present in this App's /v1/pubkeys (algorithm: {}). \
             This is advisory only — NOT auto-trusted. If you want to rely on it, \
             independently verify its fingerprint out of band (never solely against \
             this same service), then pin it via `PinnedKeyMap::with_extra_key`.",
            algorithm.as_deref().unwrap_or("unknown")
        ))
    }
}

#[async_trait]
impl AttestationKeyLookup for PubkeysEndpointLookup {
    async fn lookup_pem(&self, key_id: &str) -> Result<String, CleanLibraryError> {
        {
            let cache = self.cache.read().await;
            if let Some((pem, _, fetched_at)) = cache.get(key_id) {
                if fetched_at.elapsed() < self.ttl {
                    return Ok(pem.clone());
                }
            }
        }
        // Cache miss or stale — refresh the WHOLE catalog (small, 2-key
        // response today) rather than a per-key_id endpoint, matching what
        // `/v1/pubkeys` actually offers.
        self.fetch_and_cache_all().await?;
        let cache = self.cache.read().await;
        cache
            .get(key_id)
            .map(|(pem, _, _)| pem.clone())
            .ok_or_else(|| CleanLibraryError::AttestationInvalid {
                reason_code: "ATTESTATION_KEY_ID_UNKNOWN".to_string(),
                message: format!(
                    "key_id {key_id:?} not present in /v1/pubkeys — cannot verify \
                     (this is a permanent mismatch for this catalog snapshot, not a \
                     transient fetch failure; a genuinely new key version requires a \
                     BD-coordinated rotation event per [EphKeyDesync]). NOTE: this \
                     impl is convenience-only post-redesign (see type doc) — \
                     `verify_attestation`'s default path uses `PinnedKeyMap`, not this."
                ),
            })
    }
}

/// Verify a `SignedAttestation` envelope (`{attestation, signature_b64,
/// key_id}` — the exact shape `Verdict::attestation` carries) against a
/// key resolved via `key_lookup`.
///
/// `Ok(())` — signature verifies against the JCS-canonical bytes of the
/// `attestation` sub-object, resolved to a real key_id.
/// `Err(CleanLibraryError::AttestationInvalid)` — envelope malformed, key_id
/// unknown, or the signature genuinely does not match (permanent — do not
/// retry the same envelope).
/// `Err(CleanLibraryError::Transport)` — transient failure resolving the
/// key (network/5xx fetching `/v1/pubkeys`); retry may succeed.
pub async fn verify_attestation(
    attestation_envelope: &serde_json::Value,
    key_lookup: &dyn AttestationKeyLookup,
) -> Result<(), CleanLibraryError> {
    let malformed = |field: &str| CleanLibraryError::AttestationInvalid {
        reason_code: "ATTESTATION_ENVELOPE_MALFORMED".to_string(),
        message: format!("attestation envelope missing or wrong-typed field: {field}"),
    };

    let predicate = attestation_envelope
        .get("attestation")
        .ok_or_else(|| malformed("attestation"))?;
    let signature_b64 = attestation_envelope
        .get("signature_b64")
        .and_then(|v| v.as_str())
        .ok_or_else(|| malformed("signature_b64"))?;
    let key_id = attestation_envelope
        .get("key_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| malformed("key_id"))?;

    // Step 2 of the recipe: JCS-canonicalize the PARSED predicate. This is
    // deliberately re-derived from the parsed `Value`, not the raw wire
    // bytes — the whole point of RFC-8785 (CLEANLIB-476 on the signer side)
    // is that any conformant parse + reserialize reproduces the signer's
    // exact canonical bytes regardless of incidental wire key order.
    let canonical = serde_jcs::to_vec(predicate).map_err(|e| CleanLibraryError::AttestationInvalid {
        reason_code: "ATTESTATION_CANONICALIZATION_FAILED".to_string(),
        message: format!("JCS canonicalization of attestation predicate failed: {e}"),
    })?;

    let sig_bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, signature_b64)
        .map_err(|e| CleanLibraryError::AttestationInvalid {
            reason_code: "ATTESTATION_SIGNATURE_ENCODING_INVALID".to_string(),
            message: format!("signature_b64 is not valid base64: {e}"),
        })?;
    let signature = Signature::from_der(&sig_bytes).map_err(|e| CleanLibraryError::AttestationInvalid {
        reason_code: "ATTESTATION_SIGNATURE_ENCODING_INVALID".to_string(),
        message: format!("signature is not valid DER-encoded ECDSA: {e}"),
    })?;

    let pem = key_lookup.lookup_pem(key_id).await?;
    let verifying_key = VerifyingKey::from_public_key_pem(&pem).map_err(|e| {
        CleanLibraryError::AttestationInvalid {
            reason_code: "ATTESTATION_KEY_ENCODING_INVALID".to_string(),
            message: format!("pubkey PEM for key_id {key_id:?} is not a valid P-256 SPKI: {e}"),
        }
    })?;

    verifying_key
        .verify(&canonical, &signature)
        .map_err(|e| CleanLibraryError::AttestationInvalid {
            reason_code: "ATTESTATION_SIGNATURE_MISMATCH".to_string(),
            message: format!(
                "signature does not verify against key_id {key_id:?}'s canonical predicate: {e}"
            ),
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use p256::ecdsa::signature::Signer as _;
    use p256::ecdsa::SigningKey;
    use p256::pkcs8::EncodePublicKey;
    use rand_core_compat::OsRng;
    use std::sync::Mutex;

    // rand_core version alignment: p256's `ecdsa::signature::Signer` for
    // `SigningKey` needs an `OsRng` from the `rand_core` version p256/ecdsa
    // pin internally re-export via `elliptic_curve`. Route through the
    // crate's own re-export path so this test never drifts against a
    // separately-resolved `rand_core` major version.
    mod rand_core_compat {
        pub use p256::ecdsa::signature::rand_core::OsRng;
    }

    /// A static, in-memory [`AttestationKeyLookup`] for tests — no network.
    /// Mirrors what a caller wiring `verify_attestation` for an air-gapped /
    /// pre-provisioned-key deployment would implement.
    struct StaticKeyLookup {
        keys: HashMap<String, String>,
        lookups: Mutex<u32>,
    }

    #[async_trait]
    impl AttestationKeyLookup for StaticKeyLookup {
        async fn lookup_pem(&self, key_id: &str) -> Result<String, CleanLibraryError> {
            *self.lookups.lock().unwrap() += 1;
            self.keys.get(key_id).cloned().ok_or_else(|| {
                CleanLibraryError::AttestationInvalid {
                    reason_code: "ATTESTATION_KEY_ID_UNKNOWN".to_string(),
                    message: format!("test lookup has no key_id {key_id:?}"),
                }
            })
        }
    }

    /// Build a `{attestation, signature_b64, key_id}` envelope shaped like
    /// the App's real `SignedAttestation` wire object (see
    /// `cleanlib-cosign-signer::Attestation` — reproduced structurally here,
    /// NOT via a crate dependency, since that crate is `publish = false` /
    /// service-internal and cleanlib-client must not depend on it).
    fn sample_predicate() -> serde_json::Value {
        serde_json::json!({
            "artifact_hash": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
            "verdict_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
            "verdict_source": "allowed_no_findings",
            "verdict_evaluated_at": "1970-01-01T00:00:00Z",
            "policy_decision": "allow",
            "policy_rule_id_matched": "rule_acme_001",
            "risk_acceptance_status": "none",
            "organization_id": "org_test_acme",
            "app_version": "0.1.0",
            "served_at": "1970-01-01T00:00:00Z",
        })
    }

    /// Sign `predicate` with a freshly generated P-256 key, reproducing the
    /// exact `cleanlib-cosign-signer::LocalEcdsaSigner::sign` recipe (JCS
    /// canonical bytes -> ECDSA sign -> DER -> base64) from first principles,
    /// so this is a genuine independent-implementation check of the
    /// verify-side recipe against the signer's documented behavior, not a
    /// tautology against this module's own canonicalization call.
    fn sign_predicate(predicate: &serde_json::Value, signing_key: &SigningKey) -> (String, String) {
        let canonical = serde_jcs::to_vec(predicate).unwrap();
        let signature: Signature = signing_key.sign(&canonical);
        let sig_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, signature.to_der());
        let pem = VerifyingKey::from(signing_key)
            .to_public_key_pem(p256::pkcs8::LineEnding::LF)
            .unwrap();
        (sig_b64, pem)
    }

    #[tokio::test]
    async fn positive_real_shaped_attestation_verifies() {
        let signing_key = SigningKey::random(&mut OsRng);
        let predicate = sample_predicate();
        let (sig_b64, pem) = sign_predicate(&predicate, &signing_key);
        let key_id = "projects/cleanlibrary-prod/locations/us-central1/keyRings/\
                       cleanlibrary-signing/cryptoKeys/cleanlib-cosign-staging/cryptoKeyVersions/1";

        let envelope = serde_json::json!({
            "attestation": predicate,
            "signature_b64": sig_b64,
            "key_id": key_id,
        });
        let lookup = StaticKeyLookup {
            keys: HashMap::from([(key_id.to_string(), pem)]),
            lookups: Mutex::new(0),
        };

        verify_attestation(&envelope, &lookup)
            .await
            .expect("genuine signature over the exact predicate must verify");
        assert_eq!(*lookup.lookups.lock().unwrap(), 1);
    }

    /// Counterexample per `[Counterexample]` discipline: this MUST fail, and
    /// must fail as `AttestationInvalid` (permanent), not panic and not
    /// silently return `Ok`. This is gate 3's core safety property — a
    /// negative control catching a "verify that always passes" regression.
    #[tokio::test]
    async fn negative_wrong_key_fails_loud_not_silent() {
        let signing_key = SigningKey::random(&mut OsRng);
        let wrong_key = SigningKey::random(&mut OsRng);
        let predicate = sample_predicate();
        let (sig_b64, _real_pem) = sign_predicate(&predicate, &signing_key);
        let wrong_pem = VerifyingKey::from(&wrong_key)
            .to_public_key_pem(p256::pkcs8::LineEnding::LF)
            .unwrap();
        let key_id = "local-ecdsa-p256-test";

        let envelope = serde_json::json!({
            "attestation": predicate,
            "signature_b64": sig_b64,
            "key_id": key_id,
        });
        // The lookup resolves key_id to the WRONG key — simulating either a
        // key-catalog mixup or an attacker substituting their own key_id +
        // signature pair while a naive verifier trusts whatever key_id is
        // present without cross-checking provenance.
        let lookup = StaticKeyLookup {
            keys: HashMap::from([(key_id.to_string(), wrong_pem)]),
            lookups: Mutex::new(0),
        };

        let err = verify_attestation(&envelope, &lookup)
            .await
            .expect_err("signature signed by a different key must NOT verify");
        match err {
            CleanLibraryError::AttestationInvalid { reason_code, .. } => {
                assert_eq!(reason_code, "ATTESTATION_SIGNATURE_MISMATCH");
            }
            other => panic!("expected AttestationInvalid, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn tampered_predicate_after_signing_fails_verification() {
        // Sibling counterexample to the wrong-key case: same key, but the
        // predicate the caller hands to verify_attestation was mutated after
        // signing (e.g. a MITM or a buggy cache flipping policy_decision).
        let signing_key = SigningKey::random(&mut OsRng);
        let predicate = sample_predicate();
        let (sig_b64, pem) = sign_predicate(&predicate, &signing_key);
        let key_id = "local-ecdsa-p256-test";

        let mut tampered = predicate.clone();
        tampered["policy_decision"] = serde_json::json!("deny");
        let envelope = serde_json::json!({
            "attestation": tampered,
            "signature_b64": sig_b64,
            "key_id": key_id,
        });
        let lookup = StaticKeyLookup {
            keys: HashMap::from([(key_id.to_string(), pem)]),
            lookups: Mutex::new(0),
        };

        let err = verify_attestation(&envelope, &lookup).await.unwrap_err();
        assert!(matches!(
            err,
            CleanLibraryError::AttestationInvalid { reason_code, .. }
                if reason_code == "ATTESTATION_SIGNATURE_MISMATCH"
        ));
    }

    #[tokio::test]
    async fn unknown_key_id_is_attestation_invalid_not_transport() {
        let signing_key = SigningKey::random(&mut OsRng);
        let predicate = sample_predicate();
        let (sig_b64, _pem) = sign_predicate(&predicate, &signing_key);
        let envelope = serde_json::json!({
            "attestation": predicate,
            "signature_b64": sig_b64,
            "key_id": "some-key-id-not-in-the-catalog",
        });
        let lookup = StaticKeyLookup { keys: HashMap::new(), lookups: Mutex::new(0) };

        let err = verify_attestation(&envelope, &lookup).await.unwrap_err();
        // Permanent (catalog doesn't have this key), not a retryable transport
        // error — callers must not busy-loop retrying an unknown key_id.
        assert!(!err.is_retryable());
        assert!(matches!(err, CleanLibraryError::AttestationInvalid { .. }));
    }

    #[tokio::test]
    async fn malformed_envelope_missing_signature_field_is_rejected() {
        let envelope = serde_json::json!({
            "attestation": sample_predicate(),
            "key_id": "x",
            // signature_b64 missing entirely
        });
        let lookup = StaticKeyLookup { keys: HashMap::new(), lookups: Mutex::new(0) };
        let err = verify_attestation(&envelope, &lookup).await.unwrap_err();
        match err {
            CleanLibraryError::AttestationInvalid { reason_code, .. } => {
                assert_eq!(reason_code, "ATTESTATION_ENVELOPE_MALFORMED");
            }
            other => panic!("expected AttestationInvalid, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn key_id_lookup_is_cached_across_repeated_verifies() {
        // Not a network test (that lives in the ignored integration test
        // below), but proves the CACHING contract at the trait-usage level:
        // two verifies against the same key_id must not force two lookups
        // once the first has succeeded — this is what makes repeated
        // `Client::verify_attestation` calls in a hot loop cheap.
        let signing_key = SigningKey::random(&mut OsRng);
        let predicate = sample_predicate();
        let (sig_b64, pem) = sign_predicate(&predicate, &signing_key);
        let key_id = "local-ecdsa-p256-test";
        let envelope = serde_json::json!({
            "attestation": predicate,
            "signature_b64": sig_b64,
            "key_id": key_id,
        });
        let lookup = StaticKeyLookup {
            keys: HashMap::from([(key_id.to_string(), pem)]),
            lookups: Mutex::new(0),
        };

        verify_attestation(&envelope, &lookup).await.unwrap();
        verify_attestation(&envelope, &lookup).await.unwrap();
        // StaticKeyLookup itself doesn't cache (it's O(1) HashMap lookup by
        // design, standing in for "no caching needed for a pre-provisioned
        // bundle"); PubkeysEndpointLookup's OWN cache is exercised by the
        // `#[ignore]` live test below since it requires a real HTTP fixture.
        assert_eq!(*lookup.lookups.lock().unwrap(), 2);
    }

    /// Live integration test against a real `PubkeysEndpointLookup` — requires
    /// a reachable App instance and is gated behind `--ignored` (network
    /// dependency; this crate's default `cargo test` must stay hermetic).
    /// Exercises the TTL-cache path: first call is a real HTTP fetch, second
    /// (within TTL) must not re-fetch.
    #[tokio::test]
    #[ignore = "requires a live cleanlib-app endpoint; run with `cargo test -- --ignored`"]
    async fn pubkeys_endpoint_lookup_caches_within_ttl() {
        let base = Url::parse("https://cleanapp.clnstrt.dev").unwrap();
        let lookup = PubkeysEndpointLookup::new(&base).unwrap();
        let staging_key_id = "projects/cleanlibrary-prod/locations/us-central1/keyRings/\
                               cleanlibrary-signing/cryptoKeys/cleanlib-cosign-staging/cryptoKeyVersions/1";
        let pem1 = lookup.lookup_pem(staging_key_id).await.unwrap();
        let pem2 = lookup.lookup_pem(staging_key_id).await.unwrap();
        assert_eq!(pem1, pem2);
        assert!(pem1.contains("BEGIN PUBLIC KEY"));
    }

    // ─── Gate-3 redesign (2026-09-13, BD-ratified per CLEANLIB-379 #804236):
    // PinnedKeyMap is now the default trust root. These tests are the
    // positive + negative-control pair BD required before Test-mgr co-sign,
    // PLUS the new load-bearing structural proof that the unknown-key path
    // is genuinely fail-closed (no fetch), not just behaviorally an error. ──

    /// Positive control: the two built-in key_ids resolve to PEMs that
    /// parse as valid P-256 SubjectPublicKeyInfo — proves the compiled-in
    /// map itself is well-formed, independent of any signing/verify test.
    #[test]
    fn pinned_key_map_builtin_entries_are_well_formed() {
        for (key_id, pem) in PinnedKeyMap::builtin() {
            assert!(key_id.contains("cryptoKeyVersions"), "key_id shape: {key_id}");
            VerifyingKey::from_public_key_pem(pem)
                .unwrap_or_else(|e| panic!("built-in PEM for {key_id:?} does not parse: {e}"));
        }
    }

    /// Positive: an attestation genuinely signed by a key pinned via
    /// `with_extra_key` (standing in for a real staging/prod signature,
    /// since this test can't sign with KMS's actual private key) verifies.
    #[tokio::test]
    async fn pinned_key_map_verifies_a_pinned_extra_key() {
        let signing_key = SigningKey::random(&mut OsRng);
        let pem = VerifyingKey::from(&signing_key)
            .to_public_key_pem(p256::pkcs8::LineEnding::LF)
            .unwrap();
        let predicate = sample_predicate();
        let (sig_b64, _) = sign_predicate(&predicate, &signing_key);
        let key_id = "test-pinned-extra-key";
        let envelope = serde_json::json!({
            "attestation": predicate,
            "signature_b64": sig_b64,
            "key_id": key_id,
        });
        let map = PinnedKeyMap::default().with_extra_key(key_id, pem);

        verify_attestation(&envelope, &map)
            .await
            .expect("signature over a genuinely pinned key must verify");
    }

    /// THE core counterexample BD's redesign exists to guarantee: an unknown
    /// `key_id` must fail closed WITHOUT ever attempting a network call —
    /// this is a STRUCTURAL proof, not just a behavioral one. The runtime
    /// below has NO I/O or time driver enabled
    /// (`Builder::new_current_thread()` with neither `.enable_io()` nor
    /// `.enable_time()`); if `PinnedKeyMap::lookup_pem` attempted ANY real
    /// network operation, this would panic ("there is no reactor running")
    /// instead of returning cleanly. It returns cleanly — proving no network
    /// capability exists on this path, not merely that this particular test
    /// happened not to trigger one.
    #[test]
    fn pinned_key_map_unknown_key_fails_closed_with_no_io_driver() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .expect("bare runtime with no I/O/time driver");
        let map = PinnedKeyMap::default();
        let result = rt.block_on(map.lookup_pem("key-id-not-in-any-pinned-set"));

        let err = result.expect_err("unrecognized key_id must fail, not silently succeed");
        assert!(!err.is_retryable(), "unknown key_id is permanent, not transient");
        assert!(matches!(
            err,
            CleanLibraryError::AttestationInvalid { reason_code, .. }
                if reason_code == "ATTESTATION_KEY_ID_UNKNOWN"
        ));
    }

    /// Sibling structural proof for the KNOWN-key path: a built-in key_id
    /// resolves successfully even with NO I/O/time driver available,
    /// confirming the earlier no-panic result isn't just because the whole
    /// runtime is inert — the known-key path genuinely never touches the
    /// network either.
    #[test]
    fn pinned_key_map_known_key_resolves_with_no_io_driver() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .expect("bare runtime with no I/O/time driver");
        let map = PinnedKeyMap::default();
        let (known_key_id, _) = PinnedKeyMap::builtin()[0];
        let pem = rt
            .block_on(map.lookup_pem(known_key_id))
            .expect("built-in key_id must resolve without any network driver");
        assert!(pem.contains("BEGIN PUBLIC KEY"));
    }

    /// Full end-to-end counterexample through `verify_attestation` (not just
    /// the lookup in isolation): a well-formed, validly-signed attestation
    /// whose `key_id` simply isn't pinned must still fail closed, exactly
    /// like the PR #536 "wrong key" / "tampered predicate" counterexamples —
    /// same rigor, new failure axis (unpinned rather than wrong/tampered).
    #[tokio::test]
    async fn end_to_end_verify_fails_closed_for_unpinned_key_id() {
        let signing_key = SigningKey::random(&mut OsRng);
        let predicate = sample_predicate();
        let (sig_b64, _pem_unused) = sign_predicate(&predicate, &signing_key);
        let envelope = serde_json::json!({
            "attestation": predicate,
            "signature_b64": sig_b64,
            "key_id": "totally-unpinned-key-id",
        });
        let map = PinnedKeyMap::default(); // deliberately NOT pinning the signing key

        let err = verify_attestation(&envelope, &map).await.unwrap_err();
        assert!(!err.is_retryable());
        assert!(matches!(
            err,
            CleanLibraryError::AttestationInvalid { reason_code, .. }
                if reason_code == "ATTESTATION_KEY_ID_UNKNOWN"
        ));
    }

    /// `PubkeysEndpointLookup::describe_unknown_key` must never resemble a
    /// verify result: it returns `Option<String>` (advisory text or
    /// nothing), never a bool/PEM/Ok(()), so it structurally cannot be
    /// mistaken for — or misused as — a trust decision. This test only
    /// exercises the "server unreachable" branch (hermetic, no network); the
    /// "key found, here's the advisory" branch needs a live App and is
    /// covered by the existing `#[ignore]`'d live test's spirit (not
    /// duplicated here to keep default `cargo test` network-free).
    #[tokio::test]
    async fn describe_unknown_key_returns_none_not_a_trust_signal_when_unreachable() {
        let base = Url::parse("https://127.0.0.1.invalid.example").unwrap();
        let lookup = PubkeysEndpointLookup::new(&base).unwrap();
        let advisory = lookup.describe_unknown_key("any-key-id").await;
        assert!(
            advisory.is_none(),
            "unreachable server must yield None (no advisory), never fabricate one"
        );
    }
}