walletkit-core 0.27.1

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
//! Native request-integrity callbacks used to authenticate Flamingo connections.

use std::{
    sync::{Arc, LazyLock},
    time::Duration,
};

use tokio::sync::Semaphore;

use attested_request::{
    base::CanonicalRequest,
    sign::{SignError, SignedHeaders, Signer},
    Platform,
};
use tokio_tungstenite::tungstenite::handshake::client::Request;

/// The platform determines the native signature encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum RequestIntegrityPlatform {
    /// An App Attest assertion encoded as CBOR.
    Ios,
    /// An Android Keystore ECDSA signature encoded as DER.
    Android,
}

/// Request-integrity failures without token, key, or native diagnostic contents.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum RequestIntegrityError {
    /// The host could not prepare an integrity session.
    #[error("request integrity is unavailable")]
    Unavailable,
    /// The prepared session contains an unusable token.
    #[error("request integrity session is invalid")]
    InvalidSession,
    /// The native signer failed or returned an empty signature.
    #[error("request integrity signing failed")]
    SigningFailed,
    /// A host callback threw an unexpected exception.
    #[error("request integrity callback failed")]
    CallbackFailed,
    /// Preparing or signing exceeded the authentication deadline.
    #[error("request integrity authentication timed out")]
    TimedOut,
}

impl From<uniffi::UnexpectedUniFFICallbackError> for RequestIntegrityError {
    fn from(_: uniffi::UnexpectedUniFFICallbackError) -> Self {
        Self::CallbackFailed
    }
}

/// Signs a SHA-256 client-data digest with the key certified by the session token.
///
/// The host captures the key identifier and audience in this object. `WalletKit` never
/// receives private-key material. The callback is invoked on a blocking worker.
/// A running native signing operation cannot be cancelled when authentication times
/// out; its late result is discarded. At most four native signing calls run process-wide;
/// a timed-out call retains its slot until the native callback returns.
#[uniffi::export(with_foreign)]
pub trait RequestDigestSigner: Send + Sync {
    /// Signs exactly 32 bytes and returns the platform's native signature encoding.
    ///
    /// iOS returns an App Attest assertion; Android returns a DER ECDSA signature.
    /// The digest must be forwarded unchanged. Android must sign this precomputed hash,
    /// without hashing it again; iOS passes it directly as App Attest's `clientDataHash`.
    ///
    /// # Errors
    /// Returns [`RequestIntegrityError`] if native signing cannot complete.
    fn sign_digest(
        &self,
        client_data_hash: Vec<u8>,
    ) -> Result<Vec<u8>, RequestIntegrityError>;
}

/// A token and the signer pinned to the exact key certified by that token.
///
/// The provider must create the pair atomically so a later key rotation cannot mix them.
/// An already-returned signer must keep using its captured key. The host adapts its native
/// session to these callbacks without passing private-key material or other SDK callback types.
#[derive(Clone, uniffi::Record)]
pub struct RequestIntegritySession {
    /// A valid integrity token for the host-selected Flamingo audience.
    pub token: String,
    /// Encoding expected from the native signer.
    pub platform: RequestIntegrityPlatform,
    /// A signer capturing the matching hardware key and native signing context.
    pub signer: Arc<dyn RequestDigestSigner>,
}

/// Supplies authentication material before each WebSocket connection or reassignment.
///
/// The host owns token acquisition, refresh, audience policy, and hardware-key lifecycle.
/// It selects the audience when configuring the provider; `WalletKit` does not decode the
/// token or receive the audience or key identifier. Preparing and signing share a 30-second
/// deadline in the matcher.
#[uniffi::export(with_foreign)]
#[async_trait::async_trait]
pub trait RequestIntegrityProvider: Send + Sync {
    /// Returns a usable token and its matching signer, reusing a cached token when valid.
    ///
    /// # Errors
    /// Returns [`RequestIntegrityError`] if an integrity session is unavailable.
    async fn prepare(&self) -> Result<RequestIntegritySession, RequestIntegrityError>;
}

const AUTHENTICATION_TIMEOUT: Duration = Duration::from_secs(30);

/// Bounds native callbacks even when timed-out callers abandon their results.
static SIGNING_SLOTS: LazyLock<Arc<Semaphore>> =
    LazyLock::new(|| Arc::new(Semaphore::new(4)));

/// Signs within a shared deadline and the process-wide native callback limit.
pub(super) async fn sign_request(
    provider: Arc<dyn RequestIntegrityProvider>,
    request: Request,
) -> Result<SignedHeaders, RequestIntegrityError> {
    sign_request_with_limit(provider, request, SIGNING_SLOTS.clone()).await
}

/// Accepts an isolated limit so timeout regression tests do not share live signing slots.
async fn sign_request_with_limit(
    provider: Arc<dyn RequestIntegrityProvider>,
    request: Request,
    slots: Arc<Semaphore>,
) -> Result<SignedHeaders, RequestIntegrityError> {
    tokio::time::timeout(AUTHENTICATION_TIMEOUT, async move {
        let session = provider.prepare().await?;
        if session.token.is_empty()
            || !session
                .token
                .bytes()
                .all(|byte| (0x21..=0x7e).contains(&byte))
        {
            return Err(RequestIntegrityError::InvalidSession);
        }

        let permit = slots
            .acquire_owned()
            .await
            .map_err(|_| RequestIntegrityError::Unavailable)?;
        tokio::task::spawn_blocking(move || {
            let _permit = permit;
            let uri = request.uri();
            let scheme = match uri.scheme_str() {
                Some("ws" | "http") => "http",
                Some("wss" | "https") => "https",
                _ => return Err(RequestIntegrityError::SigningFailed),
            };
            let authority = uri
                .authority()
                .ok_or(RequestIntegrityError::SigningFailed)?;
            let canonical = CanonicalRequest::new(
                request.method().as_str(),
                scheme,
                authority.as_str(),
                uri.path(),
                uri.query(),
                b"",
            )
            .map_err(|_| RequestIntegrityError::SigningFailed)?;
            attested_request::sign::sign_request(&canonical, &session.token, &session)
                .map_err(|error| match error {
                    SignError::Signer(error) => error,
                    _ => RequestIntegrityError::SigningFailed,
                })
        })
        .await
        .map_err(|_| RequestIntegrityError::SigningFailed)?
    })
    .await
    .map_err(|_| RequestIntegrityError::TimedOut)?
}

impl Signer for RequestIntegritySession {
    type Error = RequestIntegrityError;

    fn platform(&self) -> Platform {
        match self.platform {
            RequestIntegrityPlatform::Ios => Platform::Ios,
            RequestIntegrityPlatform::Android => Platform::Android,
        }
    }

    fn sign(&self, client_data_hash: &[u8; 32]) -> Result<Vec<u8>, Self::Error> {
        let signature = self.signer.sign_digest(client_data_hash.to_vec())?;
        if signature.is_empty() {
            return Err(RequestIntegrityError::SigningFailed);
        }
        Ok(signature)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        sync::{
            atomic::{AtomicU8, Ordering},
            Condvar, Mutex,
        },
        time::SystemTime,
    };

    use attested_request::{
        base::CanonicalRequest,
        sign::SignedHeaders,
        signature::SignatureParams,
        test_util::{test_key, SoftwareSigner, TestClaims, TestIssuer},
        token::TokenVerifier,
        Platform, RejectReason, Verifier,
    };
    use tokio_tungstenite::tungstenite::{
        client::IntoClientRequest, handshake::client::Request, http,
    };

    use super::*;

    const AUDIENCE: &str = "flamingo-verifier";
    const TARGET: &str = "/proxy/a%20b/v1/matches?x=%2F&x=one+two";

    fn request(url: &str) -> Request {
        url.into_client_request().unwrap()
    }

    fn received(
        headers: &SignedHeaders,
        method: &str,
        target: &str,
    ) -> http::request::Parts {
        let mut request = http::Request::builder().method(method).uri(target);
        for (name, value) in headers.headers() {
            request = request.header(name, value);
        }
        request.body(()).unwrap().into_parts().0
    }

    struct SoftwareCallback {
        signer: SoftwareSigner,
        runtime_thread: std::thread::ThreadId,
        digests: Arc<Mutex<Vec<Vec<u8>>>>,
    }

    impl RequestDigestSigner for SoftwareCallback {
        fn sign_digest(
            &self,
            client_data_hash: Vec<u8>,
        ) -> Result<Vec<u8>, RequestIntegrityError> {
            assert_ne!(std::thread::current().id(), self.runtime_thread);
            let digest = client_data_hash.as_slice().try_into().unwrap();
            self.digests.lock().unwrap().push(client_data_hash);
            Ok(self.signer.sign(&digest).unwrap())
        }
    }

    struct RotatingProvider {
        issuer: TestIssuer,
        platform: Platform,
        next_key: AtomicU8,
        runtime_thread: std::thread::ThreadId,
        digests: Arc<Mutex<Vec<Vec<u8>>>>,
    }

    impl RotatingProvider {
        fn new(platform: Platform) -> Self {
            Self {
                issuer: TestIssuer::new("https://attestation.example"),
                platform,
                next_key: AtomicU8::new(1),
                runtime_thread: std::thread::current().id(),
                digests: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn verifier(&self, scheme: &str, authority: &str) -> Verifier {
            let tokens = TokenVerifier::new(
                [(
                    self.issuer.issuer.clone(),
                    Arc::new(self.issuer.keys()) as _,
                )],
                [AUDIENCE.to_owned()],
            )
            .unwrap();
            Verifier::builder(tokens, authority)
                .scheme(scheme)
                .build()
                .unwrap()
        }
    }

    #[async_trait::async_trait]
    impl RequestIntegrityProvider for RotatingProvider {
        async fn prepare(
            &self,
        ) -> Result<RequestIntegritySession, RequestIntegrityError> {
            let key = self.next_key.fetch_add(1, Ordering::Relaxed);
            let signer =
                SoftwareSigner::new(test_key(&format!("device-{key}")), self.platform);
            let token = self.issuer.mint(&TestClaims::valid(
                AUDIENCE,
                self.platform,
                signer.verifying_key(),
                SystemTime::now(),
            ));
            Ok(RequestIntegritySession {
                token,
                platform: match self.platform {
                    Platform::Ios => RequestIntegrityPlatform::Ios,
                    Platform::Android => RequestIntegrityPlatform::Android,
                },
                signer: Arc::new(SoftwareCallback {
                    signer,
                    runtime_thread: self.runtime_thread,
                    digests: self.digests.clone(),
                }),
            })
        }
    }

    /// Verifies the exact upgrade emitted by the matcher, including encoded path and query values.
    #[tokio::test]
    #[allow(clippy::result_large_err)] // Tungstenite fixes the handshake callback's error type.
    async fn matcher_upgrade_verifies_after_crossing_the_network() {
        use super::super::{FlamingoError, FlamingoMatcher, MatchClient};
        use tokio::net::TcpListener;
        use tokio_tungstenite::accept_hdr_async;

        for platform in [Platform::Ios, Platform::Android] {
            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
            let authority = listener.local_addr().unwrap().to_string();
            let (sent, received) = tokio::sync::oneshot::channel();
            let server = tokio::spawn(async move {
                let (stream, _) = listener.accept().await.unwrap();
                let socket =
                    accept_hdr_async(stream, move |upgrade: &Request, response| {
                        sent.send(upgrade.clone()).unwrap();
                        Ok(response)
                    })
                    .await
                    .unwrap();
                drop(socket);
            });
            let provider = Arc::new(RotatingProvider::new(platform));
            let mut matcher = FlamingoMatcher::new(&format!(
                "http://{authority}/proxy/a%20b/?x=%2F&x=one+two"
            ))
            .unwrap();
            matcher.integrity_provider = Some(provider.clone());
            let matcher = matcher.dangerously_skip_measurements().unwrap();
            let result = tokio::time::timeout(Duration::from_secs(5), async {
                matcher.client().await.unwrap().connect().await
            })
            .await
            .unwrap();
            assert!(matches!(result, Err(FlamingoError::Transport { .. })));
            let upgrade = received.await.unwrap();
            server.await.unwrap();
            let (mut parts, ()) = upgrade.into_parts();
            assert_eq!(parts.uri.path_and_query().unwrap().as_str(), TARGET);
            let verifier = provider.verifier("http", &authority);
            verifier.verify(&parts, b"").await.unwrap();
            parts.uri = "/tampered/v1/matches?x=%2F&x=one+two".parse().unwrap();
            assert_eq!(
                verifier.verify(&parts, b"").await.unwrap_err().reason,
                RejectReason::SignatureInvalid
            );
        }
    }

    #[tokio::test]
    async fn software_callbacks_verify_for_the_final_websocket_request() {
        for platform in [Platform::Ios, Platform::Android] {
            for (url, scheme, authority) in [
                (
                    format!("wss://Verifier.Example:443{TARGET}"),
                    "https",
                    "verifier.example",
                ),
                (
                    format!("ws://Verifier.Example:80{TARGET}"),
                    "http",
                    "verifier.example",
                ),
                (
                    format!("wss://Verifier.Example:8443{TARGET}"),
                    "https",
                    "verifier.example:8443",
                ),
            ] {
                let provider = Arc::new(RotatingProvider::new(platform));
                let signed =
                    sign_request(provider.clone(), request(&url)).await.unwrap();
                let context = provider
                    .verifier(scheme, authority)
                    .verify(&received(&signed, "GET", TARGET), b"")
                    .await
                    .unwrap();
                assert_eq!(context.device.platform, platform);
                assert_eq!(context.device.audience, AUDIENCE);
                assert_eq!(context.request_binding, signed.request_binding);
                assert_eq!(
                    context.device.key.verifying_key(),
                    test_key("device-1").verifying_key()
                );

                let params = SignatureParams::parse(&signed.signature_input).unwrap();
                let canonical = CanonicalRequest::new(
                    "GET",
                    scheme,
                    authority,
                    "/proxy/a%20b/v1/matches",
                    Some("x=%2F&x=one+two"),
                    b"",
                )
                .unwrap();
                let digest = canonical
                    .signature_base(&params, &signed.integrity_token)
                    .client_data_hash();
                assert_eq!(*provider.digests.lock().unwrap(), [digest.to_vec()]);
            }
        }
    }

    #[tokio::test]
    async fn reconnects_prepare_new_key_bound_sessions_and_fresh_signatures() {
        let provider = Arc::new(RotatingProvider::new(Platform::Android));
        let url = "wss://verifier.example/v1/matches";
        let first = sign_request(provider.clone(), request(url)).await.unwrap();
        let second = sign_request(provider.clone(), request(url)).await.unwrap();
        assert_eq!(provider.next_key.load(Ordering::Relaxed), 3);
        assert_ne!(first.integrity_token, second.integrity_token);
        assert_ne!(first.signature_input, second.signature_input);
        assert_ne!(first.request_binding, second.request_binding);
        let verifier = provider.verifier("https", "verifier.example");
        for headers in [&first, &second] {
            verifier
                .verify(&received(headers, "GET", "/v1/matches"), b"")
                .await
                .unwrap();
        }
        let mut mixed = received(&second, "GET", "/v1/matches");
        mixed
            .headers
            .insert("integrity-token", first.integrity_token.parse().unwrap());
        assert_eq!(
            verifier.verify(&mixed, b"").await.unwrap_err().reason,
            RejectReason::SignatureInvalid
        );
    }

    #[tokio::test]
    async fn signatures_reject_changes_to_covered_request_components() {
        let provider = Arc::new(RotatingProvider::new(Platform::Android));
        let signed = sign_request(
            provider.clone(),
            request(&format!("wss://verifier.example{TARGET}")),
        )
        .await
        .unwrap();
        let verifier = provider.verifier("https", "verifier.example");
        for (method, target, body) in [
            ("POST", TARGET, b"".as_slice()),
            (
                "GET",
                "/proxy/a%20b/v1/other?x=%2F&x=one+two",
                b"".as_slice(),
            ),
            (
                "GET",
                "/proxy/a%20b/v1/matches?x=%2f&x=one+two",
                b"".as_slice(),
            ),
            ("GET", TARGET, b"changed".as_slice()),
        ] {
            assert_eq!(
                verifier
                    .verify(&received(&signed, method, target), body)
                    .await
                    .unwrap_err()
                    .reason,
                RejectReason::SignatureInvalid
            );
        }
        for (scheme, authority) in
            [("wss", "verifier.example"), ("https", "other.example")]
        {
            assert_eq!(
                provider
                    .verifier(scheme, authority)
                    .verify(&received(&signed, "GET", TARGET), b"")
                    .await
                    .unwrap_err()
                    .reason,
                RejectReason::SignatureInvalid
            );
        }
    }

    /// Returns a selected typed error from the provider callback.
    struct FailingProvider(RequestIntegrityError);

    #[async_trait::async_trait]
    impl RequestIntegrityProvider for FailingProvider {
        async fn prepare(
            &self,
        ) -> Result<RequestIntegritySession, RequestIntegrityError> {
            Err(self.0)
        }
    }

    #[tokio::test]
    async fn preserves_provider_failure() {
        assert!(matches!(
            sign_request(
                Arc::new(FailingProvider(RequestIntegrityError::Unavailable)),
                request("wss://verifier.example/v1/matches")
            )
            .await,
            Err(RequestIntegrityError::Unavailable)
        ));
    }

    /// Unexpected native diagnostics are hidden and preserve the same classification at either callback.
    #[tokio::test]
    async fn unexpected_callback_failures_are_neutral_and_do_not_expose_details() {
        let error = RequestIntegrityError::from(
            uniffi::UnexpectedUniFFICallbackError::new("private native diagnostic"),
        );
        assert_eq!(error, RequestIntegrityError::CallbackFailed);
        assert_eq!(error.to_string(), "request integrity callback failed");
        for provider in [
            Arc::new(FailingProvider(error)) as Arc<dyn RequestIntegrityProvider>,
            fixed_provider("opaque-token", Err(error)),
        ] {
            assert_eq!(
                sign_request(provider, request("wss://verifier.example/v1/matches"))
                    .await,
                Err(RequestIntegrityError::CallbackFailed),
            );
        }
    }

    struct PendingProvider;

    #[async_trait::async_trait]
    impl RequestIntegrityProvider for PendingProvider {
        async fn prepare(
            &self,
        ) -> Result<RequestIntegritySession, RequestIntegrityError> {
            std::future::pending().await
        }
    }

    #[tokio::test(start_paused = true)]
    async fn times_out_a_provider_that_never_returns() {
        let started = tokio::time::Instant::now();
        assert_eq!(
            sign_request(
                Arc::new(PendingProvider),
                request("wss://verifier.example/v1/matches")
            )
            .await,
            Err(RequestIntegrityError::TimedOut)
        );
        assert_eq!(started.elapsed(), AUTHENTICATION_TIMEOUT);
    }

    struct FixedProvider(RequestIntegritySession);

    #[async_trait::async_trait]
    impl RequestIntegrityProvider for FixedProvider {
        async fn prepare(
            &self,
        ) -> Result<RequestIntegritySession, RequestIntegrityError> {
            Ok(self.0.clone())
        }
    }

    struct FixedSigner(Result<Vec<u8>, RequestIntegrityError>);

    impl RequestDigestSigner for FixedSigner {
        fn sign_digest(&self, _: Vec<u8>) -> Result<Vec<u8>, RequestIntegrityError> {
            self.0.clone()
        }
    }

    fn fixed_provider(
        token: &str,
        signature: Result<Vec<u8>, RequestIntegrityError>,
    ) -> Arc<dyn RequestIntegrityProvider> {
        Arc::new(FixedProvider(RequestIntegritySession {
            token: token.to_string(),
            platform: RequestIntegrityPlatform::Android,
            signer: Arc::new(FixedSigner(signature)),
        }))
    }

    #[tokio::test]
    async fn rejects_unusable_tokens_before_signing() {
        for token in ["", " ", "token\r\ninjected: value", "non-ascii-\u{00e9}"] {
            assert!(matches!(
                sign_request(
                    fixed_provider(token, Err(RequestIntegrityError::SigningFailed),),
                    request("wss://verifier.example/v1/matches")
                )
                .await,
                Err(RequestIntegrityError::InvalidSession)
            ));
        }
    }

    #[tokio::test]
    async fn preserves_signer_errors_and_rejects_empty_signatures() {
        for (signature, expected) in [
            (
                Err(RequestIntegrityError::SigningFailed),
                RequestIntegrityError::SigningFailed,
            ),
            (
                Err(RequestIntegrityError::Unavailable),
                RequestIntegrityError::Unavailable,
            ),
            (Ok(Vec::new()), RequestIntegrityError::SigningFailed),
        ] {
            assert!(matches!(
                sign_request(fixed_provider("opaque-token", signature),
                    request("wss://verifier.example/v1/matches")).await,
                Err(actual) if actual == expected
            ));
        }
    }

    struct BlockingSigner {
        release: Arc<(Mutex<bool>, Condvar)>,
        entered: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
        finished: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
    }

    impl RequestDigestSigner for BlockingSigner {
        fn sign_digest(&self, _: Vec<u8>) -> Result<Vec<u8>, RequestIntegrityError> {
            self.entered
                .lock()
                .unwrap()
                .take()
                .unwrap()
                .send(())
                .unwrap();
            let (released, condition) = &*self.release;
            let _guard = condition
                .wait_while(released.lock().unwrap(), |ready| !*ready)
                .unwrap();
            self.finished
                .lock()
                .unwrap()
                .take()
                .unwrap()
                .send(())
                .unwrap();
            Ok(vec![1])
        }
    }

    #[tokio::test(start_paused = true)]
    async fn discards_a_native_signature_that_finishes_after_the_deadline() {
        let release = Arc::new((Mutex::new(false), Condvar::new()));
        let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
        let (finished_tx, finished_rx) = tokio::sync::oneshot::channel();
        let provider = Arc::new(FixedProvider(RequestIntegritySession {
            token: "opaque-token".to_owned(),
            platform: RequestIntegrityPlatform::Android,
            signer: Arc::new(BlockingSigner {
                release: release.clone(),
                entered: Mutex::new(Some(entered_tx)),
                finished: Mutex::new(Some(finished_tx)),
            }),
        }));
        let slots = Arc::new(Semaphore::new(1));
        let signing = tokio::spawn(sign_request_with_limit(
            provider,
            request("wss://verifier.example/v1/matches"),
            slots.clone(),
        ));
        entered_rx.await.unwrap();
        tokio::time::advance(AUTHENTICATION_TIMEOUT).await;
        let result = signing.await.unwrap();
        let queued = tokio::spawn(sign_request_with_limit(
            fixed_provider("opaque-token", Ok(vec![1])),
            request("wss://verifier.example/v1/matches"),
            slots.clone(),
        ));
        tokio::task::yield_now().await;
        tokio::time::advance(AUTHENTICATION_TIMEOUT).await;
        let queued_result = queued.await.unwrap();
        *release.0.lock().unwrap() = true;
        release.1.notify_one();
        finished_rx.await.unwrap();
        assert_eq!(result, Err(RequestIntegrityError::TimedOut));
        assert_eq!(queued_result, Err(RequestIntegrityError::TimedOut));
        // The native worker releases its slot after returning, which can follow the signal.
        tokio::time::resume();
        assert!(sign_request_with_limit(
            fixed_provider("opaque-token", Ok(vec![1])),
            request("wss://verifier.example/v1/matches"),
            slots,
        )
        .await
        .is_ok());
    }
}