walletkit-core 0.23.0

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
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
//! Attested `Flamingo` matching in preparation for zero-knowledge proof generation.
//!
//! This module deliberately knows nothing about Orb PCP storage. Its caller supplies the live
//! image and the credential material obtained through the platform's Oxide/OrbKit adapter. The
//! module owns assignment, attestation verification, sealing, transport, response opening, and
//! match-token verification.

use std::{collections::HashMap, sync::Arc};

use async_trait::async_trait;
use flamingo_verifier_client::{
    Config, Error as ClientError, FlamingoVerifierClient, PcrMeasurement,
    VerifiedAssignment,
};
use flamingo_verifier_sealed_types::{FailureReason, MatchInputs, MatchResult};
use reqwest::{
    header::{HeaderMap, HeaderName, HeaderValue, COOKIE},
    Url,
};
use thiserror::Error;
use tokio::sync::OnceCell;

/// A simple wrapper around of `FlamingoVerifierClient`. Flamingo Verifier is a cloud TEE service for attested embedding generation and comparison.
#[derive(Debug, uniffi::Object)]
pub struct FlamingoMatcher {
    host_url: Url,
    config: Option<Config>,
    headers: HeaderMap,
    client: OnceCell<FlamingoVerifierClient>,
}

/// Inputs for one attested `Flamingo` 3-way match.
///
/// `credential_image` and `hashes_json` must come from the same enrolled Orb PCP. In particular,
/// `hashes_json` must contain the exact archive bytes, not parsed and reserialized JSON.
#[derive(Debug, uniffi::Record)]
pub struct FlamingoMatchRequest {
    /// Raw liveness image bytes captured for this request.
    pub live_image: Vec<u8>,
    /// Raw `thumbnail.png` bytes decrypted from the enrolled Orb PCP.
    pub credential_image: Vec<u8>,
    /// Exact raw `hashes.json` bytes extracted from the enrolled Orb PCP.
    pub hashes_json: Vec<u8>,
    /// Optional second liveness frame for the `LightGuard` flow.
    pub light_guard_image: Option<Vec<u8>>,
    /// Raw challenge image bytes downloaded from the relying party.
    pub challenge_image: Vec<u8>,
    /// Minimum similarity required by the RP. Must be finite and between zero and one.
    pub match_threshold: f32,
}

/// A match token whose signing-key attestation and signature were verified.
///
/// Foreign callers receive an opaque handle. The token and signing-key attestation remain
/// together in Rust for proof generation and eventual relay of the attestation to the RP.
#[derive(Debug, uniffi::Object)]
pub struct VerifiedMatchToken {
    token: Vec<u8>,
    signing_key_attestation: Vec<u8>,
}

/// The outcome of the TEE match phase.
#[derive(Debug, uniffi::Enum)]
pub enum FlamingoMatchOutcome {
    /// The enclave issued a token and `WalletKit` verified it against an attested signing key.
    Matched(Arc<VerifiedMatchToken>),
    /// The response reported a rejection. An unsigned rejection does not authenticate its sender.
    Rejected(FlamingoMatchRejection),
}

/// A rejection reason reported in an encrypted match response.
///
/// The reason is unsigned; it is not proof that the attested enclave issued it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum FlamingoMatchRejection {
    /// The sealed inputs were malformed.
    MalformedInputs,
    /// The PCP hashes file was invalid or did not contain the thumbnail commitment.
    InvalidHashesJson,
    /// The credential image did not match the PCP thumbnail commitment.
    ThumbnailHashMismatch,
    /// At least one comparison scored below the requested threshold.
    MatchBelowThreshold,
    /// The enclave could not obtain a usable comparison score from the images.
    ImageAnalysisFailed,
}

/// Failures while configuring or performing a match request.
#[derive(Debug, Error, uniffi::Error)]
pub enum FlamingoError {
    /// A caller-supplied value cannot form a valid match request.
    #[error("invalid {attribute}: {reason}")]
    InvalidInput {
        /// Name of the invalid field.
        attribute: String,
        /// Why the value was rejected.
        reason: String,
    },
    /// The verifier configuration was not valid.
    #[error("invalid Flamingo verifier configuration: {0}")]
    Configuration(String),
    /// Assignment, attestation, transport, channel opening, or token verification failed.
    #[error("Flamingo verifier request failed: {0}")]
    Verifier(String),
}

#[async_trait]
trait MatchClient: Sync {
    type Assignment: Send + Sync;

    async fn request_assignment(&self) -> Result<Self::Assignment, ClientError>;

    async fn request_match(
        &self,
        assignment: &Self::Assignment,
        inputs: &MatchInputs,
    ) -> Result<MatchResult, ClientError>;
}

#[uniffi::export(async_runtime = "tokio")]
impl FlamingoMatcher {
    /// Creates an instance with default values, use `with_measurements` and `with_headers` for customization.
    ///
    /// # Errors
    ///
    /// Returns [`FlamingoError::Configuration`] if the URL is not a valid HTTP(S) URL.
    #[uniffi::constructor]
    pub fn new(host_url: &str) -> Result<Self, FlamingoError> {
        let host_url = Url::parse(host_url)
            .map_err(|error| FlamingoError::Configuration(error.to_string()))?;
        if !matches!(host_url.scheme(), "http" | "https")
            || host_url.host_str().is_none()
        {
            return Err(FlamingoError::Configuration(
                "host_url must be an absolute HTTP(S) URL".to_string(),
            ));
        }
        Ok(Self {
            host_url,
            config: None,
            headers: HeaderMap::new(),
            client: OnceCell::new(),
        })
    }

    /// Returns a new instance with trusted measurements keyed by PCR index.
    ///
    /// PCR0, PCR1, and PCR2 must be supplied from an approved enclave build. Additional entries
    /// are also pinned. It's the user's responsibility to ensure the measurements are from a trusted enclave and match the verifier's expectations.
    ///
    /// # Errors
    /// Returns [`FlamingoError::Configuration`] if no measurement is set.
    pub fn with_measurements(
        &self,
        measurements: HashMap<u32, Vec<u8>>,
    ) -> Result<Self, FlamingoError> {
        Ok(Self {
            host_url: self.host_url.clone(),
            config: Some(matcher_config(self.host_url.as_str(), measurements)?),
            headers: self.headers.clone(),
            client: OnceCell::new(),
        })
    }

    /// Returns a new instance with these default headers, replacing any previously configured set.
    ///
    /// Use this to set authorization, client name, or other headers. The `Cookie` header is not allowed; the client manages affinity cookies automatically.
    ///
    /// # Errors
    /// Returns [`FlamingoError::Configuration`] for invalid names/values, case-insensitive duplicate
    /// names, or a caller-supplied `Cookie` header (the client owns affinity cookies).
    pub fn with_headers(
        &self,
        headers: HashMap<String, String>,
    ) -> Result<Self, FlamingoError> {
        Ok(Self {
            host_url: self.host_url.clone(),
            config: self.config.clone(),
            headers: parse_headers(headers)?,
            client: OnceCell::new(),
        })
    }

    /// Performs an attested 3-way embedding match.
    ///
    /// - Fetches the enclave assignment and verifies its attestation against the trusted PCRs.
    /// - Encrypts and sends the match inputs using the enclave's attested public key.
    /// - Decrypts the result and, on success, verifies the token's signature and signing-key attestation.
    ///
    /// # Errors
    ///
    /// Returns [`FlamingoError::InvalidInput`] before making a network request when a caller value
    /// is unusable, or [`FlamingoError::Configuration`] if trusted measurements are missing.
    /// Other failures are returned as [`FlamingoError::Verifier`].
    pub async fn perform_match(
        &self,
        request: FlamingoMatchRequest,
    ) -> Result<FlamingoMatchOutcome, FlamingoError> {
        perform_match(self.client().await?, request).await
    }
}

impl FlamingoMatcher {
    async fn client(&self) -> Result<&FlamingoVerifierClient, FlamingoError> {
        self.client
            .get_or_try_init(|| async {
                let config = self.config.clone().ok_or_else(|| {
                    FlamingoError::Configuration(
                        "trusted enclave measurements must be supplied with with_measurements"
                            .to_string(),
                    )
                })?;
                let http = reqwest::Client::builder().default_headers(self.headers.clone());
                FlamingoVerifierClient::with_http_client_builder(config, http)
                    .map_err(|error| FlamingoError::Verifier(error.to_string()))
            })
            .await
    }
}

impl FlamingoMatchRequest {
    fn validate(&self) -> Result<(), FlamingoError> {
        for (attribute, bytes) in [
            ("live_image", self.live_image.as_slice()),
            ("credential_image", self.credential_image.as_slice()),
            ("hashes_json", self.hashes_json.as_slice()),
        ] {
            if bytes.is_empty() {
                return Err(FlamingoError::InvalidInput {
                    attribute: attribute.to_string(),
                    reason: "must not be empty".to_string(),
                });
            }
        }

        if self.challenge_image.is_empty() {
            return Err(FlamingoError::InvalidInput {
                attribute: "challenge_image".to_string(),
                reason: "must not be empty".to_string(),
            });
        }

        if self.light_guard_image.as_ref().is_some_and(Vec::is_empty) {
            return Err(FlamingoError::InvalidInput {
                attribute: "light_guard_image".to_string(),
                reason: "must not be empty when provided".to_string(),
            });
        }

        if !self.match_threshold.is_finite()
            || !(0.0..=1.0).contains(&self.match_threshold)
        {
            return Err(FlamingoError::InvalidInput {
                attribute: "match_threshold".to_string(),
                reason: "must be finite and between 0 and 1 inclusive".to_string(),
            });
        }

        Ok(())
    }

    fn into_inputs(self) -> MatchInputs {
        MatchInputs {
            live_image: self.live_image,
            credential_image: self.credential_image,
            light_guard_image: self.light_guard_image,
            hashes_json: self.hashes_json,
            challenge_image: self.challenge_image,
            match_threshold: self.match_threshold,
        }
    }
}

impl VerifiedMatchToken {
    /// Borrows the encoded COSE/CBOR token for proof generation.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.token
    }

    /// Borrows the signing-key attestation to relay alongside the generated proof.
    #[must_use]
    pub fn signing_key_attestation(&self) -> &[u8] {
        &self.signing_key_attestation
    }
}

impl From<FailureReason> for FlamingoMatchRejection {
    fn from(value: FailureReason) -> Self {
        match value {
            FailureReason::MalformedInputs => Self::MalformedInputs,
            FailureReason::InvalidHashesJson => Self::InvalidHashesJson,
            FailureReason::ThumbnailHashMismatch => Self::ThumbnailHashMismatch,
            FailureReason::MatchBelowThreshold => Self::MatchBelowThreshold,
            FailureReason::ImageAnalysisFailed => Self::ImageAnalysisFailed,
        }
    }
}

#[async_trait]
impl MatchClient for FlamingoVerifierClient {
    type Assignment = VerifiedAssignment;

    async fn request_assignment(&self) -> Result<Self::Assignment, ClientError> {
        self.request_assignment().await
    }

    async fn request_match(
        &self,
        assignment: &Self::Assignment,
        inputs: &MatchInputs,
    ) -> Result<MatchResult, ClientError> {
        self.request_match(assignment, inputs).await
    }
}

fn parse_headers(headers: HashMap<String, String>) -> Result<HeaderMap, FlamingoError> {
    let mut parsed = HeaderMap::new();
    for (name, value) in headers {
        let name = HeaderName::from_bytes(name.as_bytes()).map_err(|_| {
            FlamingoError::Configuration("invalid HTTP header name".to_string())
        })?;
        if name == COOKIE {
            return Err(FlamingoError::Configuration(
                "Cookie is managed by the client's affinity cookie store".to_string(),
            ));
        }
        let mut value = HeaderValue::from_str(&value).map_err(|_| {
            FlamingoError::Configuration("invalid HTTP header value".to_string())
        })?;
        value.set_sensitive(true);
        if parsed.insert(name, value).is_some() {
            return Err(FlamingoError::Configuration(
                "duplicate HTTP header name (names are case-insensitive)".to_string(),
            ));
        }
    }
    Ok(parsed)
}

fn matcher_config(
    host_url: &str,
    measurements: HashMap<u32, Vec<u8>>,
) -> Result<Config, FlamingoError> {
    for index in 0..=2 {
        if !measurements.contains_key(&index) {
            return Err(FlamingoError::Configuration(format!(
                "PCR{index} must be supplied"
            )));
        }
    }
    let mut pcrs = Vec::with_capacity(measurements.len());
    for (index, measurement) in measurements {
        if measurement.len() != 48 {
            return Err(FlamingoError::Configuration(format!(
                "PCR{index} must be exactly 48 bytes"
            )));
        }
        if measurement.iter().all(|byte| *byte == 0) {
            return Err(FlamingoError::Configuration(format!(
                "PCR{index} must be nonzero; debug enclaves are not accepted"
            )));
        }
        pcrs.push(PcrMeasurement::new(index, measurement));
    }
    pcrs.sort_unstable_by_key(|pcr| pcr.index);
    Config::new(host_url, vec![pcrs])
        .map_err(|error| FlamingoError::Configuration(error.to_string()))
}

async fn perform_match<C: MatchClient>(
    client: &C,
    request: FlamingoMatchRequest,
) -> Result<FlamingoMatchOutcome, FlamingoError> {
    request.validate()?;
    let request = request.into_inputs();
    let mut reassigned = false;

    loop {
        let assignment = client
            .request_assignment()
            .await
            .map_err(|error| verifier_error(&error))?;

        match client.request_match(&assignment, &request).await {
            Ok(MatchResult::Success(statement)) => {
                return Ok(FlamingoMatchOutcome::Matched(Arc::new(
                    VerifiedMatchToken {
                        token: statement.token.into_bytes(),
                        signing_key_attestation: statement.signing_key_attestation,
                    },
                )));
            }
            Ok(MatchResult::Failed(reason)) => {
                return Ok(FlamingoMatchOutcome::Rejected(reason.into()));
            }
            Err(ClientError::ReassignRequired) if !reassigned => reassigned = true,
            Err(error) => return Err(verifier_error(&error)),
        }
    }
}

fn verifier_error(error: &ClientError) -> FlamingoError {
    FlamingoError::Verifier(error.to_string())
}

#[cfg(test)]
mod tests {
    use std::{
        collections::{HashMap, VecDeque},
        sync::{
            atomic::{AtomicUsize, Ordering},
            Mutex,
        },
    };

    use flamingo_verifier_client::Error as ClientError;
    use flamingo_verifier_protocol::match_token::MatchToken;
    use flamingo_verifier_sealed_types::{
        AttestedStatement, FailureReason, MatchInputs, MatchResult,
    };

    use super::{
        perform_match, FlamingoError, FlamingoMatchOutcome, FlamingoMatchRejection,
        FlamingoMatchRequest, FlamingoMatcher, MatchClient,
    };

    struct FakeClient {
        assignments: AtomicUsize,
        results: Mutex<VecDeque<Result<MatchResult, ClientError>>>,
    }

    impl FakeClient {
        fn new(
            results: impl IntoIterator<Item = Result<MatchResult, ClientError>>,
        ) -> Self {
            Self {
                assignments: AtomicUsize::new(0),
                results: Mutex::new(results.into_iter().collect()),
            }
        }
    }

    #[async_trait::async_trait]
    impl MatchClient for FakeClient {
        type Assignment = usize;

        async fn request_assignment(&self) -> Result<Self::Assignment, ClientError> {
            Ok(self.assignments.fetch_add(1, Ordering::Relaxed))
        }

        async fn request_match(
            &self,
            _assignment: &Self::Assignment,
            _inputs: &MatchInputs,
        ) -> Result<MatchResult, ClientError> {
            self.results
                .lock()
                .expect("fake result lock should not be poisoned")
                .pop_front()
                .expect("test should provide one result per request")
        }
    }

    fn request() -> FlamingoMatchRequest {
        FlamingoMatchRequest {
            live_image: b"live".to_vec(),
            credential_image: b"credential".to_vec(),
            hashes_json: br#"{"thumbnail.png":"00"}"#.to_vec(),
            light_guard_image: None,
            challenge_image: b"challenge".to_vec(),
            match_threshold: 0.7,
        }
    }

    fn measurements() -> HashMap<u32, Vec<u8>> {
        HashMap::from([(0, vec![1; 48]), (1, vec![2; 48]), (2, vec![3; 48])])
    }

    fn headers() -> HashMap<String, String> {
        HashMap::from([
            ("Authorization".to_string(), "Bearer test-token".to_string()),
            ("client-name".to_string(), "test-client".to_string()),
        ])
    }

    #[test]
    fn custom_measurements_preserve_required_and_additional_pcrs() {
        let mut pins = measurements();
        pins.insert(8, vec![4; 48]);
        let config =
            super::matcher_config("https://verifier.example.com", pins).unwrap();
        let json = serde_json::to_value(config).unwrap();
        assert_eq!(json["allowed_pcr_configs"].as_array().unwrap().len(), 1);
        assert_eq!(json["allowed_pcr_configs"][0].as_array().unwrap().len(), 4);
        for (position, (index, measurement)) in
            [(0, [1; 48]), (1, [2; 48]), (2, [3; 48]), (8, [4; 48])]
                .into_iter()
                .enumerate()
        {
            assert_eq!(json["allowed_pcr_configs"][0][position]["index"], index);
            assert_eq!(
                json["allowed_pcr_configs"][0][position]["value"],
                hex::encode(measurement)
            );
        }
    }

    #[test]
    fn rejects_zero_or_malformed_measurements() {
        let matcher = FlamingoMatcher::new("https://verifier.example.com").unwrap();
        for index in [0, 1, 2, 8] {
            for invalid in [vec![0; 48], vec![], vec![1; 47], vec![1; 49]] {
                let mut pins = measurements();
                pins.insert(index, invalid);
                assert!(matches!(
                    matcher.with_measurements(pins),
                    Err(FlamingoError::Configuration(_))
                ));
            }
        }
    }

    #[test]
    fn rejects_missing_required_measurements() {
        let matcher = FlamingoMatcher::new("https://verifier.example.com").unwrap();
        assert!(matches!(
            matcher.with_measurements(HashMap::new()),
            Err(FlamingoError::Configuration(_))
        ));
        for index in 0..3 {
            let mut pins = measurements();
            pins.remove(&index);
            let error = matcher.with_measurements(pins).unwrap_err();
            assert!(matches!(error, FlamingoError::Configuration(_)));
            assert!(error.to_string().contains(&format!("PCR{index}")));
        }
    }

    #[test]
    fn rejects_an_invalid_host_url() {
        for url in ["not a URL", "/relative", "ftp://verifier.example.com"] {
            assert!(matches!(
                FlamingoMatcher::new(url),
                Err(FlamingoError::Configuration(_))
            ));
        }
    }

    #[test]
    fn rejects_invalid_duplicate_and_cookie_headers_without_exposing_values() {
        let matcher = FlamingoMatcher::new("https://verifier.example.com").unwrap();
        for headers in [
            HashMap::from([("bad name".to_string(), "secret".to_string())]),
            HashMap::from([("authorization".to_string(), "secret\nvalue".to_string())]),
            HashMap::from([
                ("Authorization".to_string(), "secret".to_string()),
                ("authorization".to_string(), "secret".to_string()),
            ]),
            HashMap::from([("cOoKiE".to_string(), "secret".to_string())]),
        ] {
            let error = matcher.with_headers(headers).unwrap_err();
            assert!(matches!(error, FlamingoError::Configuration(_)));
            assert!(!format!("{error:?}").contains("secret"));
        }
    }

    #[tokio::test]
    async fn fluent_configuration_is_order_independent_and_preserves_originals() {
        let original = FlamingoMatcher::new("https://verifier.example.com").unwrap();
        let first = original
            .with_measurements(measurements())
            .unwrap()
            .with_headers(headers())
            .unwrap();
        let second = original
            .with_headers(headers())
            .unwrap()
            .with_measurements(measurements())
            .unwrap();
        assert_eq!(
            serde_json::to_value(&first.config).unwrap(),
            serde_json::to_value(&second.config).unwrap()
        );
        assert_eq!(first.headers, second.headers);
        assert!(original.config.is_none());
        assert!(original.headers.is_empty());
        assert!(first.client.get().is_none());
        assert!(second.client.get().is_none());

        let (left, right) = tokio::join!(first.client(), first.client());
        assert!(std::ptr::eq(left.unwrap(), right.unwrap()));
        assert!(!format!("{first:?}").contains("test-token"));

        let updated = first.with_headers(HashMap::new()).unwrap();
        assert!(updated.client.get().is_none());
        assert!(updated.headers.is_empty());
        assert!(!first.headers.is_empty());
        assert!(!std::ptr::eq(
            first.client().await.unwrap(),
            updated.client().await.unwrap()
        ));
    }

    #[tokio::test]
    async fn missing_measurements_fail_before_any_request() {
        let mut server = mockito::Server::new_async().await;
        let assignment = server
            .mock("POST", "/v1/enclave-assignment")
            .expect(0)
            .create_async()
            .await;
        let matcher = FlamingoMatcher::new(&server.url())
            .unwrap()
            .with_headers(headers())
            .unwrap();
        assert!(matches!(
            matcher.perform_match(request()).await,
            Err(FlamingoError::Configuration(_))
        ));
        assert!(matcher.client.get().is_none());
        assignment.assert_async().await;
        drop(server);
    }

    #[tokio::test]
    async fn http_defaults_and_affinity_cookies_cover_both_routes() {
        let mut server = mockito::Server::new_async().await;
        let assignment = server
            .mock("POST", "/v1/flamingo/v1/enclave-assignment")
            .match_header("authorization", "Bearer test-token")
            .match_header("client-name", "test-client")
            .with_header("set-cookie", "AWSALB=assigned-pod; Path=/")
            .with_status(204)
            .expect(2)
            .create_async()
            .await;
        let match_route = server
            .mock("POST", "/v1/flamingo/v1/matches")
            .match_header("authorization", "Bearer test-token")
            .match_header("client-name", "test-client")
            .match_header("cookie", "AWSALB=assigned-pod")
            .with_status(409)
            .expect(2)
            .create_async()
            .await;
        let matcher = FlamingoMatcher::new(&format!("{}/v1/flamingo/", server.url()))
            .unwrap()
            .with_measurements(measurements())
            .unwrap()
            .with_headers(headers())
            .unwrap();
        let client = matcher.client().await.unwrap();
        // Exercise the configured HTTP transport without fabricating a trusted Nitro attestation.
        // The separate retry tests below cover the match orchestration.
        let (http, _) = client.build_assignment_request().build_split();
        for _ in 0..2 {
            assert_eq!(
                client
                    .build_assignment_request()
                    .send()
                    .await
                    .unwrap()
                    .status(),
                204
            );
            assert_eq!(
                http.post(format!("{}/v1/flamingo/v1/matches", server.url()))
                    .send()
                    .await
                    .unwrap()
                    .status(),
                409
            );
        }
        assignment.assert_async().await;
        match_route.assert_async().await;
        drop(server);
    }

    #[tokio::test]
    async fn rejects_a_legacy_assignment_before_sending_images() {
        let mut server = mockito::Server::new_async().await;
        let assignment = server
            .mock("POST", "/v1/enclave-assignment")
            .match_header("authorization", "Bearer test-token")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"attestation":"YXR0ZXN0YXRpb24="}"#)
            .expect(1)
            .create_async()
            .await;
        let image_upload = server
            .mock("POST", "/v1/matches")
            .expect(0)
            .create_async()
            .await;
        let matcher = FlamingoMatcher::new(&server.url())
            .unwrap()
            .with_measurements(measurements())
            .unwrap()
            .with_headers(headers())
            .unwrap();

        let error = matcher.perform_match(request()).await.unwrap_err();

        assert!(matches!(error, FlamingoError::Verifier(_)));
        assignment.assert_async().await;
        image_upload.assert_async().await;
        drop(server);
    }

    #[tokio::test]
    async fn returns_a_verified_token_after_the_client_verifies_success() {
        let client = FakeClient::new([Ok(MatchResult::Success(AttestedStatement {
            token: MatchToken::from_bytes(b"signed-token".to_vec()),
            signing_key_attestation: b"signing-key-attestation".to_vec(),
        }))]);

        let outcome = perform_match(&client, request())
            .await
            .expect("match should succeed");

        let FlamingoMatchOutcome::Matched(token) = outcome else {
            panic!("expected a matched outcome");
        };
        assert_eq!(token.as_bytes(), b"signed-token");
        assert_eq!(token.signing_key_attestation(), b"signing-key-attestation");
        assert_eq!(client.assignments.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn returns_a_typed_sealed_rejection() {
        let client = FakeClient::new([Ok(MatchResult::Failed(
            FailureReason::ThumbnailHashMismatch,
        ))]);

        let outcome = perform_match(&client, request())
            .await
            .expect("a sealed rejection is an outcome");

        assert!(matches!(
            outcome,
            FlamingoMatchOutcome::Rejected(
                FlamingoMatchRejection::ThumbnailHashMismatch
            )
        ));
    }

    #[tokio::test]
    async fn reassigns_and_reseals_exactly_once() {
        let client = FakeClient::new([
            Err(ClientError::ReassignRequired),
            Ok(MatchResult::Failed(FailureReason::MatchBelowThreshold)),
        ]);

        let outcome = perform_match(&client, request())
            .await
            .expect("fresh assignment should recover the match request");

        assert!(matches!(
            outcome,
            FlamingoMatchOutcome::Rejected(FlamingoMatchRejection::MatchBelowThreshold)
        ));
        assert_eq!(client.assignments.load(Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn does_not_retry_a_second_stale_assignment() {
        let client = FakeClient::new([
            Err(ClientError::ReassignRequired),
            Err(ClientError::ReassignRequired),
        ]);

        let error = perform_match(&client, request())
            .await
            .expect_err("a second stale assignment should be surfaced");

        assert!(matches!(error, FlamingoError::Verifier(_)));
        assert_eq!(client.assignments.load(Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn rejects_a_non_finite_threshold_before_assignment() {
        let client = FakeClient::new([]);
        let mut request = request();
        request.match_threshold = f32::NAN;

        let error = perform_match(&client, request).await.expect_err(
            "NaN would bypass enclave comparisons and must be rejected locally",
        );

        assert!(matches!(
            error,
            FlamingoError::InvalidInput {
                attribute,
                ..
            } if attribute == "match_threshold"
        ));
        assert_eq!(client.assignments.load(Ordering::Relaxed), 0);
    }
}