1
//! Biometric manager — cross-platform state for the biometric-auth
2
//! surface (`SUPER_PLAN_2` §1 feature 4 + research/02).
3
//!
4
//! **Request-driven**, unlike the continuous `GeolocationManager`. The
5
//! three callers are:
6
//!
7
//! - A **callback** invokes `App::request_biometric_auth(prompt)` (e.g. the `AzulVault` unlock
8
//!   button). The OS draws its own modal sheet; the app cannot skin it.
9
//!
10
//! - The **platform backend** (`dll/src/desktop/extra/biometric/<plat>.rs`) shows the prompt (iOS /
11
//!   macOS `LAContext.evaluatePolicy`, Android `BiometricPrompt.authenticate`, Windows
12
//!   `UserConsentVerifier`, Linux polkit / PAM) and, when the user responds, parks the outcome in
13
//!   the async result channel [`push_biometric_result`]. It also writes the sync availability probe
14
//!   via [`BiometricManager::set_availability`].
15
//!
16
//! - The dll **layout pass** drains the channel once per frame via [`drain_biometric_results`] and
17
//!   applies the latest through [`BiometricManager::set_last_result`]; callbacks then read it with
18
//!   `CallbackInfo::get_biometric_result()` and the device capability via the sync availability
19
//!   accessor.
20
//!
21
//! No platform deps (`SUPER_PLAN_2` §0.5); the async-result channel is
22
//! copied verbatim from `geolocation.rs`.
23

            
24
use alloc::vec::Vec;
25

            
26
// `BiometricKind` / `BiometricResult` / `BiometricPrompt` live in
27
// `azul-core` so the request config can cross the FFI without a cyclic
28
// dep on `azul-layout`. Re-exported here for the existing
29
// `azul_layout::managers::biometric::*` import paths.
30
pub use azul_core::biometric::{BiometricKind, BiometricPrompt, BiometricResult};
31
use azul_core::{
32
    dom::DomNodeId,
33
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
34
    task::Instant,
35
};
36

            
37
/// Cross-platform biometric state. One per `App` — the OS exposes a
38
/// single per-process authentication surface, not per-window.
39
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
40
pub struct BiometricManager {
41
    /// Outcome of the most recent `request_biometric_auth`, or `None`
42
    /// until the first request completes. Read by callbacks via
43
    /// `CallbackInfo::get_biometric_result()`.
44
    pub last_result: Option<BiometricResult>,
45
    /// Cached sync availability probe — what the device *can* do
46
    /// (`Face` / `Fingerprint` / `Iris` / `NotAvailable`). The backend
47
    /// refreshes it on startup and after enrollment changes; callbacks
48
    /// read it to decide whether to even offer biometric unlock.
49
    pub availability: BiometricKind,
50
    /// Prompts dispatched to the native backend whose outcome has not been
51
    /// folded back yet (MWA-A1b). While non-zero the capability pump keeps
52
    /// its timer armed so the reply reaches callbacks in an idle app.
53
    pub in_flight: u32,
54
    /// `true` when a prompt outcome was folded since the last event pass
55
    /// (set on EVERY completion, even a repeated identical outcome — the
56
    /// user re-authenticated and the callback must hear about it). Read by
57
    /// the `EventProvider` impl (`EventType::BiometricResult`), cleared by
58
    /// [`clear_pending_event`](Self::clear_pending_event).
59
    pub pending_event: bool,
60
}
61

            
62
impl Default for BiometricManager {
63
7705
    fn default() -> Self {
64
7705
        Self {
65
7705
            last_result: None,
66
7705
            availability: BiometricKind::NotAvailable,
67
7705
            in_flight: 0,
68
7705
            pending_event: false,
69
7705
        }
70
7705
    }
71
}
72

            
73
impl BiometricManager {
74
    #[must_use]
75
7704
    pub fn new() -> Self {
76
7704
        Self::default()
77
7704
    }
78

            
79
    /// Most recent auth outcome, or `None` until the first request
80
    /// resolves.
81
    #[must_use]
82
94
    pub const fn last_result(&self) -> Option<BiometricResult> {
83
94
        self.last_result
84
94
    }
85

            
86
    /// Device capability probe (sync). `NotAvailable` until the backend
87
    /// reports otherwise.
88
    #[must_use]
89
109
    pub const fn availability(&self) -> BiometricKind {
90
109
        self.availability
91
109
    }
92

            
93
    /// `true` if the device has a usable biometric sensor.
94
    #[must_use]
95
34
    pub const fn is_available(&self) -> bool {
96
34
        self.availability.is_available()
97
34
    }
98

            
99
    /// Platform backend records the device's biometric capability.
100
    /// Returns `true` if it changed, so the caller can relayout to
101
    /// reflect a newly-enrolled (or newly-removed) sensor.
102
69
    pub fn set_availability(&mut self, kind: BiometricKind) -> bool {
103
69
        let changed = self.availability != kind;
104
69
        self.availability = kind;
105
69
        changed
106
69
    }
107

            
108
    /// Apply the outcome the backend delivered for the user's request.
109
    /// Returns `true` if it differs from the previous outcome (so the
110
    /// window can be marked dirty to re-render the unlocked / denied
111
    /// state).
112
205
    pub fn set_last_result(&mut self, result: BiometricResult) -> bool {
113
205
        let changed = self.last_result != Some(result);
114
205
        self.last_result = Some(result);
115
        // MWA-A1b: every completion fires an event (even an identical
116
        // repeat outcome — it answers a fresh request) and retires one
117
        // in-flight prompt.
118
205
        self.pending_event = true;
119
205
        self.in_flight = self.in_flight.saturating_sub(1);
120
205
        changed
121
205
    }
122

            
123
    /// The pump dispatched `n` prompts to the native backend; keep the
124
    /// timer armed until their outcomes fold back (MWA-A1b).
125
31
    pub const fn mark_requests_dispatched(&mut self, n: u32) {
126
31
        self.in_flight = self.in_flight.saturating_add(n);
127
31
    }
128

            
129
    /// Clear the pending-event flag. The dll calls this after the event
130
    /// pass has collected the `BiometricResult` event.
131
156
    pub const fn clear_pending_event(&mut self) {
132
156
        self.pending_event = false;
133
156
    }
134

            
135
    /// `true` while a dispatched prompt's outcome is still outstanding
136
    /// (MWA-A1b arming signal).
137
    #[must_use]
138
28
    pub const fn has_pending_async(&self) -> bool {
139
28
        self.in_flight > 0
140
28
    }
141

            
142
    /// `true` if the last attempt unlocked successfully (biometric match
143
    /// or OS passcode fallback). Convenience for the vault gate.
144
    #[must_use]
145
40
    pub const fn last_was_success(&self) -> bool {
146
36
        matches!(self.last_result, Some(r) if r.is_success())
147
40
    }
148
}
149

            
150
impl EventProvider for BiometricManager {
151
    /// Yield a window-level `BiometricResult` event when a prompt outcome
152
    /// was folded since the last pass (target = root; read the outcome via
153
    /// `CallbackInfo::get_biometric_result` inside the callback).
154
161
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
155
161
        if self.pending_event {
156
12
            alloc::vec![SyntheticEvent::new(
157
12
                EventType::BiometricResult,
158
12
                CoreEventSource::User,
159
                DomNodeId::ROOT,
160
12
                timestamp,
161
12
                EventData::None,
162
            )]
163
        } else {
164
149
            Vec::new()
165
        }
166
161
    }
167
}
168

            
169
// ────────── Async result channel (platform backend → manager) ─────────
170
//
171
// The OS prompt's reply block / `AuthenticationCallback` fires on an
172
// arbitrary thread with no handle to the live `BiometricManager` (it
173
// lives inside the window's `LayoutWindow`). The backend parks each
174
// result here; the layout pass drains it once per frame via
175
// [`drain_biometric_results`] and applies the latest through
176
// [`BiometricManager::set_last_result`]. Pure Rust — no platform
177
// dependency (SUPER_PLAN_2 §0.5). Mirrors the geolocation manager's
178
// async-fix channel.
179

            
180
static PENDING_RESULTS: std::sync::Mutex<Vec<BiometricResult>> = std::sync::Mutex::new(Vec::new());
181

            
182
/// Park a biometric result delivered by a platform backend (in the dll).
183
/// Thread-safe; recovers from a poisoned lock so one panicking applier
184
/// can't wedge delivery forever.
185
174
pub fn push_biometric_result(result: BiometricResult) {
186
174
    let mut q = PENDING_RESULTS
187
174
        .lock()
188
174
        .unwrap_or_else(std::sync::PoisonError::into_inner);
189
174
    q.push(result);
190
174
}
191

            
192
/// Drain every result parked by [`push_biometric_result`], in arrival
193
/// order. Called once per layout pass; the caller applies them through
194
/// [`BiometricManager::set_last_result`] (the last one wins).
195
17
pub fn drain_biometric_results() -> Vec<BiometricResult> {
196
17
    let mut q = PENDING_RESULTS
197
17
        .lock()
198
17
        .unwrap_or_else(std::sync::PoisonError::into_inner);
199
17
    core::mem::take(&mut *q)
200
17
}
201

            
202
// ────────── Request channel (callback → platform backend) ─────────────
203
//
204
// The reverse direction: a callback (e.g. an unlock button's `on_click`)
205
// calls `CallbackInfo::request_biometric_auth(prompt)`, which parks the
206
// prompt here. The dll layout pass drains it via
207
// [`drain_biometric_requests`] and dispatches each to the native backend
208
// (`dll::desktop::extra::biometric::request`), which shows the OS prompt
209
// and later parks the outcome back through [`push_biometric_result`].
210
// Decoupling via a channel keeps the request callable from any callback
211
// without threading the window's backend handle through `CallbackInfo`,
212
// and keeps `azul-layout` platform-free (SUPER_PLAN_2 §0.5).
213

            
214
static PENDING_REQUESTS: std::sync::Mutex<Vec<BiometricPrompt>> = std::sync::Mutex::new(Vec::new());
215

            
216
/// Queue a biometric-auth request from a callback. Picked up by the dll
217
/// layout pass and dispatched to the native prompt. Thread-safe;
218
/// poison-recovering.
219
114
pub fn push_biometric_request(prompt: BiometricPrompt) {
220
114
    let mut q = PENDING_REQUESTS
221
114
        .lock()
222
114
        .unwrap_or_else(std::sync::PoisonError::into_inner);
223
114
    q.push(prompt);
224
114
}
225

            
226
/// Drain every request queued by [`push_biometric_request`], in arrival
227
/// order. Called once per layout pass; the dll dispatches each to the
228
/// platform backend.
229
11
pub fn drain_biometric_requests() -> Vec<BiometricPrompt> {
230
11
    let mut q = PENDING_REQUESTS
231
11
        .lock()
232
11
        .unwrap_or_else(std::sync::PoisonError::into_inner);
233
11
    core::mem::take(&mut *q)
234
11
}
235

            
236
/// MWA-C-biometric: true while requests are parked in the channel but not
237
/// yet dispatched.
238
///
239
/// The capability pump's arming check must count these —
240
/// `has_pending_async` only sees `in_flight` (post-dispatch), so a prompt
241
/// queued MID-pass (after the top-of-pass pump already ran) would otherwise
242
/// wait for an unrelated event before ever being shown.
243
9
pub fn has_queued_requests() -> bool {
244
9
    PENDING_REQUESTS
245
9
        .lock()
246
9
        .map_or_else(|e| !e.into_inner().is_empty(), |q| !q.is_empty())
247
9
}
248

            
249
#[cfg(test)]
250
mod tests {
251
    use super::*;
252

            
253
    #[test]
254
1
    fn manager_defaults_to_unavailable_and_no_result() {
255
1
        let mgr = BiometricManager::new();
256
1
        assert_eq!(mgr.availability(), BiometricKind::NotAvailable);
257
1
        assert!(!mgr.is_available());
258
1
        assert_eq!(mgr.last_result(), None);
259
1
        assert!(!mgr.last_was_success());
260
1
    }
261

            
262
    #[test]
263
1
    fn set_availability_returns_change_flag() {
264
1
        let mut mgr = BiometricManager::new();
265
1
        assert!(mgr.set_availability(BiometricKind::Face));
266
1
        assert!(mgr.is_available());
267
1
        assert_eq!(mgr.availability(), BiometricKind::Face);
268
        // Same value again — no change.
269
1
        assert!(!mgr.set_availability(BiometricKind::Face));
270
        // Different value — change.
271
1
        assert!(mgr.set_availability(BiometricKind::Fingerprint));
272
1
    }
273

            
274
    #[test]
275
1
    fn set_last_result_returns_change_flag() {
276
1
        let mut mgr = BiometricManager::new();
277
1
        assert!(mgr.set_last_result(BiometricResult::Failed));
278
1
        assert_eq!(mgr.last_result(), Some(BiometricResult::Failed));
279
1
        assert!(!mgr.last_was_success());
280
        // Re-applying the same outcome is not a change.
281
1
        assert!(!mgr.set_last_result(BiometricResult::Failed));
282
        // A new outcome is a change, and Authenticated is a success.
283
1
        assert!(mgr.set_last_result(BiometricResult::Authenticated));
284
1
        assert!(mgr.last_was_success());
285
1
    }
286

            
287
    #[test]
288
1
    fn passcode_fallback_counts_as_success() {
289
1
        let mut mgr = BiometricManager::new();
290
1
        mgr.set_last_result(BiometricResult::FellBackToPasscode);
291
1
        assert!(mgr.last_was_success());
292
1
        assert!(BiometricResult::FellBackToPasscode.is_success());
293
        // Cancelled / Failed / Unavailable / Error are not successes.
294
4
        for r in [
295
1
            BiometricResult::Cancelled,
296
1
            BiometricResult::Failed,
297
1
            BiometricResult::Unavailable,
298
1
            BiometricResult::Error,
299
        ] {
300
4
            assert!(!r.is_success(), "{r:?} must not be a success");
301
        }
302
1
    }
303

            
304
    #[test]
305
1
    fn async_results_round_trip_through_manager() {
306
        // The channel is process-global; serialize against every other
307
        // channel test, then clear any residue.
308
1
        let _guard = autotest_generated::lock_channels();
309
1
        drop(drain_biometric_results());
310

            
311
1
        push_biometric_result(BiometricResult::Failed);
312
1
        push_biometric_result(BiometricResult::Authenticated); // last wins
313
1
        let drained = drain_biometric_results();
314
1
        assert_eq!(drained.len(), 2, "both parked results drain in order");
315
1
        assert_eq!(drained[0], BiometricResult::Failed);
316
1
        assert_eq!(drained[1], BiometricResult::Authenticated);
317

            
318
        // Applying them reflects in last_result() — what the layout pass does.
319
1
        let mut mgr = BiometricManager::new();
320
3
        for r in &drained {
321
2
            mgr.set_last_result(*r);
322
2
        }
323
1
        assert_eq!(
324
1
            mgr.last_result(),
325
            Some(BiometricResult::Authenticated),
326
            "the last applied result wins"
327
        );
328
1
        assert!(mgr.last_was_success());
329

            
330
        // A second drain is empty — the queue was taken, not copied.
331
1
        assert!(drain_biometric_results().is_empty());
332
1
    }
333

            
334
    #[test]
335
1
    fn requests_round_trip_through_channel() {
336
        // Process-global; serialize against every other channel test, then
337
        // clear residue.
338
1
        let _guard = autotest_generated::lock_channels();
339
1
        drop(drain_biometric_requests());
340

            
341
1
        push_biometric_request(BiometricPrompt::new("Unlock A".into()));
342
1
        push_biometric_request(BiometricPrompt::new("Unlock B".into()));
343
1
        let drained = drain_biometric_requests();
344
1
        assert_eq!(drained.len(), 2, "both queued requests drain in order");
345
1
        assert_eq!(drained[0].reason.as_str(), "Unlock A");
346
1
        assert_eq!(drained[1].reason.as_str(), "Unlock B");
347

            
348
        // A second drain is empty — the queue was taken, not copied.
349
1
        assert!(drain_biometric_requests().is_empty());
350
1
    }
351

            
352
    #[test]
353
1
    fn biometric_prompt_defaults_and_constructor() {
354
1
        let d = BiometricPrompt::default();
355
1
        assert!(!d.allow_device_credential);
356
1
        assert_eq!(d.reason.as_str(), "");
357

            
358
1
        let p = BiometricPrompt::new("Unlock your vault".into());
359
1
        assert_eq!(p.reason.as_str(), "Unlock your vault");
360
1
        assert_eq!(p.cancel_label.as_str(), "");
361
1
        assert!(!p.allow_device_credential);
362
1
    }
363
}
364

            
365
#[cfg(test)]
366
mod pump_provider_tests {
367
    use azul_core::task::{Instant, SystemTick};
368

            
369
    use super::*;
370

            
371
5
    fn ts() -> Instant {
372
5
        Instant::Tick(SystemTick::new(0))
373
5
    }
374

            
375
    #[test]
376
1
    fn in_flight_tracks_dispatch_and_completion() {
377
1
        let mut mgr = BiometricManager::new();
378
1
        assert!(!mgr.has_pending_async());
379
1
        mgr.mark_requests_dispatched(2);
380
1
        assert!(mgr.has_pending_async());
381
1
        mgr.set_last_result(BiometricResult::Cancelled);
382
1
        assert!(mgr.has_pending_async(), "one of two still outstanding");
383
1
        mgr.set_last_result(BiometricResult::Authenticated);
384
1
        assert!(!mgr.has_pending_async());
385
        // saturates — an unsolicited result never underflows
386
1
        mgr.set_last_result(BiometricResult::Failed);
387
1
        assert!(!mgr.has_pending_async());
388
1
    }
389

            
390
    #[test]
391
1
    fn every_completion_fires_an_event_even_identical_repeats() {
392
1
        let mut mgr = BiometricManager::new();
393
1
        assert!(mgr.get_pending_events(ts()).is_empty());
394
1
        mgr.set_last_result(BiometricResult::Cancelled);
395
1
        assert_eq!(mgr.get_pending_events(ts()).len(), 1);
396
1
        mgr.clear_pending_event();
397
1
        assert!(mgr.get_pending_events(ts()).is_empty());
398
        // identical outcome answering a FRESH prompt → fresh event
399
1
        mgr.set_last_result(BiometricResult::Cancelled);
400
1
        assert_eq!(mgr.get_pending_events(ts()).len(), 1);
401
1
        assert_eq!(
402
1
            mgr.get_pending_events(ts())[0].event_type,
403
            EventType::BiometricResult
404
        );
405
1
    }
406
}
407

            
408
#[cfg(test)]
409
mod autotest_generated {
410
    use alloc::string::{String, ToString};
411
    use std::sync::{Mutex, PoisonError};
412

            
413
    use azul_core::task::SystemTick;
414

            
415
    use super::*;
416

            
417
    /// The result/request channels are process-global statics and `cargo
418
    /// test` runs tests in parallel threads, so EVERY test that pushes to
419
    /// or drains a channel must hold this lock — otherwise one test's
420
    /// pushes land inside another's drain window. Shared with the
421
    /// hand-written `tests` module above.
422
    static CHANNEL_LOCK: Mutex<()> = Mutex::new(());
423

            
424
    pub(super) fn lock_channels() -> std::sync::MutexGuard<'static, ()> {
425
        CHANNEL_LOCK.lock().unwrap_or_else(PoisonError::into_inner)
426
    }
427

            
428
    fn ts() -> Instant {
429
        Instant::Tick(SystemTick::new(0))
430
    }
431

            
432
    const ALL_KINDS: [BiometricKind; 4] = [
433
        BiometricKind::NotAvailable,
434
        BiometricKind::Fingerprint,
435
        BiometricKind::Face,
436
        BiometricKind::Iris,
437
    ];
438

            
439
    const ALL_RESULTS: [BiometricResult; 6] = [
440
        BiometricResult::Authenticated,
441
        BiometricResult::Failed,
442
        BiometricResult::Cancelled,
443
        BiometricResult::FellBackToPasscode,
444
        BiometricResult::Unavailable,
445
        BiometricResult::Error,
446
    ];
447

            
448
    // ── constructor ────────────────────────────────────────────────────
449

            
450
    #[test]
451
    fn new_equals_default_and_holds_the_zero_state_invariants() {
452
        let a = BiometricManager::new();
453
        let b = BiometricManager::default();
454
        assert_eq!(a, b, "new() must be exactly default()");
455
        // Every field is at its documented zero state.
456
        assert_eq!(a.last_result, None);
457
        assert_eq!(a.availability, BiometricKind::NotAvailable);
458
        assert_eq!(a.in_flight, 0);
459
        assert!(!a.pending_event);
460
        // ...and the accessors agree with the fields.
461
        assert_eq!(a.last_result(), None);
462
        assert_eq!(a.availability(), BiometricKind::NotAvailable);
463
        assert!(!a.is_available());
464
        assert!(!a.has_pending_async());
465
        assert!(!a.last_was_success());
466
        assert!(
467
            a.get_pending_events(ts()).is_empty(),
468
            "a fresh manager owes the event pass nothing"
469
        );
470
        // Repeated construction is deterministic.
471
        assert_eq!(BiometricManager::new(), BiometricManager::new());
472
    }
473

            
474
    // ── getters / predicates ───────────────────────────────────────────
475

            
476
    #[test]
477
    fn getters_mirror_the_public_fields_for_every_kind_result_pair() {
478
        for kind in ALL_KINDS {
479
            for result in ALL_RESULTS {
480
                let mut mgr = BiometricManager::new();
481
                mgr.set_availability(kind);
482
                mgr.set_last_result(result);
483

            
484
                assert_eq!(mgr.availability(), kind, "{kind:?}");
485
                assert_eq!(mgr.availability(), mgr.availability, "{kind:?}");
486
                assert_eq!(
487
                    mgr.is_available(),
488
                    kind.is_available(),
489
                    "is_available must delegate to the kind ({kind:?})"
490
                );
491
                assert_eq!(mgr.last_result(), Some(result), "{result:?}");
492
                assert_eq!(mgr.last_result(), mgr.last_result, "{result:?}");
493
                assert_eq!(
494
                    mgr.last_was_success(),
495
                    result.is_success(),
496
                    "last_was_success must delegate to the result ({result:?})"
497
                );
498
                // The two axes are independent: an unavailable sensor can
499
                // still hold a successful (passcode-fallback) outcome.
500
                assert_eq!(mgr.availability(), kind);
501
            }
502
        }
503
    }
504

            
505
    #[test]
506
    fn is_available_is_true_for_every_real_sensor_and_false_only_for_none() {
507
        let mut mgr = BiometricManager::new();
508
        assert!(!mgr.is_available(), "known-false: the default");
509
        mgr.set_availability(BiometricKind::Fingerprint);
510
        assert!(mgr.is_available(), "known-true: a real sensor");
511

            
512
        for kind in ALL_KINDS {
513
            let mut mgr = BiometricManager::new();
514
            mgr.set_availability(kind);
515
            assert_eq!(
516
                mgr.is_available(),
517
                kind != BiometricKind::NotAvailable,
518
                "only NotAvailable is unavailable ({kind:?})"
519
            );
520
        }
521
    }
522

            
523
    #[test]
524
    fn last_was_success_is_false_while_no_request_has_resolved() {
525
        // `matches!(None, Some(r) if ..)` must not be read as "unknown".
526
        let mgr = BiometricManager::new();
527
        assert_eq!(mgr.last_result(), None);
528
        assert!(
529
            !mgr.last_was_success(),
530
            "an unauthenticated vault must stay locked before the first attempt"
531
        );
532
        // An available sensor alone never implies a success.
533
        let mut mgr = BiometricManager::new();
534
        mgr.set_availability(BiometricKind::Face);
535
        assert!(mgr.is_available());
536
        assert!(!mgr.last_was_success());
537
    }
538

            
539
    #[test]
540
    fn only_authenticated_and_passcode_fallback_unlock_the_gate() {
541
        for result in ALL_RESULTS {
542
            let mut mgr = BiometricManager::new();
543
            mgr.set_last_result(result);
544
            let expected = matches!(
545
                result,
546
                BiometricResult::Authenticated | BiometricResult::FellBackToPasscode
547
            );
548
            assert_eq!(
549
                mgr.last_was_success(),
550
                expected,
551
                "{result:?} must {} unlock the gate",
552
                if expected { "" } else { "not" }
553
            );
554
        }
555
    }
556

            
557
    // ── set_availability / set_last_result change flags ─────────────────
558

            
559
    #[test]
560
    fn set_availability_change_flag_is_exactly_inequality_for_all_pairs() {
561
        for from in ALL_KINDS {
562
            for to in ALL_KINDS {
563
                let mut mgr = BiometricManager::new();
564
                mgr.availability = from;
565
                let changed = mgr.set_availability(to);
566
                assert_eq!(
567
                    changed,
568
                    from != to,
569
                    "set_availability({to:?}) over {from:?} reported the wrong change flag"
570
                );
571
                assert_eq!(mgr.availability(), to, "the write must land regardless");
572
                // Re-applying the same value is never a change.
573
                assert!(!mgr.set_availability(to), "idempotent re-apply of {to:?}");
574
                assert_eq!(mgr.availability(), to);
575
            }
576
        }
577
    }
578

            
579
    #[test]
580
    fn set_availability_does_not_disturb_the_async_or_result_state() {
581
        let mut mgr = BiometricManager::new();
582
        mgr.mark_requests_dispatched(3);
583
        mgr.set_last_result(BiometricResult::Authenticated);
584
        mgr.clear_pending_event();
585
        let before = mgr;
586

            
587
        mgr.set_availability(BiometricKind::Iris);
588

            
589
        assert_eq!(mgr.last_result, before.last_result, "result untouched");
590
        assert_eq!(mgr.in_flight, before.in_flight, "in_flight untouched");
591
        assert_eq!(
592
            mgr.pending_event, before.pending_event,
593
            "an availability probe is not a prompt outcome — it must not fire an event"
594
        );
595
    }
596

            
597
    #[test]
598
    fn set_last_result_change_flag_is_exactly_inequality_for_all_pairs() {
599
        for first in ALL_RESULTS {
600
            for second in ALL_RESULTS {
601
                let mut mgr = BiometricManager::new();
602
                assert!(
603
                    mgr.set_last_result(first),
604
                    "None -> Some({first:?}) is always a change"
605
                );
606
                let changed = mgr.set_last_result(second);
607
                assert_eq!(
608
                    changed,
609
                    first != second,
610
                    "set_last_result({second:?}) over {first:?} reported the wrong change flag"
611
                );
612
                assert_eq!(mgr.last_result(), Some(second), "the write must land");
613
            }
614
        }
615
    }
616

            
617
    #[test]
618
    fn every_completion_arms_a_pending_event_even_when_unchanged() {
619
        // The change flag ("re-render?") and the event flag ("tell the
620
        // callback?") are different questions — a repeat outcome answers a
621
        // FRESH prompt and must still be delivered.
622
        for result in ALL_RESULTS {
623
            let mut mgr = BiometricManager::new();
624
            mgr.set_last_result(result);
625
            mgr.clear_pending_event();
626

            
627
            let changed = mgr.set_last_result(result);
628
            assert!(
629
                !changed,
630
                "identical outcome is not a state change ({result:?})"
631
            );
632
            assert!(
633
                mgr.pending_event,
634
                "a repeated {result:?} must still fire an event"
635
            );
636
            assert_eq!(mgr.get_pending_events(ts()).len(), 1);
637
        }
638
    }
639

            
640
    // ── mark_requests_dispatched (numeric) ─────────────────────────────
641

            
642
    #[test]
643
    fn mark_requests_dispatched_zero_is_a_no_op() {
644
        let mut mgr = BiometricManager::new();
645
        mgr.mark_requests_dispatched(0);
646
        assert_eq!(mgr.in_flight, 0, "0 prompts dispatched adds nothing");
647
        assert!(
648
            !mgr.has_pending_async(),
649
            "dispatching nothing must not arm the pump's timer"
650
        );
651

            
652
        mgr.mark_requests_dispatched(1);
653
        mgr.mark_requests_dispatched(0);
654
        assert_eq!(mgr.in_flight, 1, "0 must not clear an outstanding prompt");
655
        assert!(mgr.has_pending_async());
656
    }
657

            
658
    #[test]
659
    fn mark_requests_dispatched_saturates_at_u32_max_instead_of_overflowing() {
660
        let mut mgr = BiometricManager::new();
661
        mgr.mark_requests_dispatched(u32::MAX);
662
        assert_eq!(mgr.in_flight, u32::MAX);
663
        assert!(mgr.has_pending_async());
664

            
665
        // A debug-build `+` here would panic; saturating_add must clamp.
666
        mgr.mark_requests_dispatched(1);
667
        assert_eq!(mgr.in_flight, u32::MAX, "saturates, does not wrap to 0");
668
        mgr.mark_requests_dispatched(u32::MAX);
669
        assert_eq!(mgr.in_flight, u32::MAX, "still clamped");
670
        assert!(
671
            mgr.has_pending_async(),
672
            "wrapping to 0 here would disarm the pump and strand the reply"
673
        );
674
    }
675

            
676
    #[test]
677
    fn mark_requests_dispatched_accumulates_across_calls() {
678
        let mut mgr = BiometricManager::new();
679
        for _ in 0..10u32 {
680
            mgr.mark_requests_dispatched(7);
681
        }
682
        assert_eq!(mgr.in_flight, 70);
683
        // Boundary: u32::MAX - 1 then +1 lands exactly on MAX, not past it.
684
        let mut mgr = BiometricManager::new();
685
        mgr.mark_requests_dispatched(u32::MAX - 1);
686
        mgr.mark_requests_dispatched(1);
687
        assert_eq!(mgr.in_flight, u32::MAX);
688
    }
689

            
690
    #[test]
691
    fn unsolicited_results_saturate_in_flight_at_zero_instead_of_underflowing() {
692
        // A backend that parks a result for a prompt we never dispatched
693
        // (or a duplicate delivery) must not wrap in_flight to u32::MAX —
694
        // that would arm the capability timer forever.
695
        let mut mgr = BiometricManager::new();
696
        assert_eq!(mgr.in_flight, 0);
697
        for result in ALL_RESULTS {
698
            mgr.set_last_result(result);
699
            assert_eq!(mgr.in_flight, 0, "underflow on unsolicited {result:?}");
700
            assert!(!mgr.has_pending_async());
701
        }
702
    }
703

            
704
    #[test]
705
    fn each_completion_retires_exactly_one_in_flight_prompt() {
706
        let mut mgr = BiometricManager::new();
707
        mgr.mark_requests_dispatched(3);
708
        assert_eq!(mgr.in_flight, 3);
709

            
710
        mgr.set_last_result(BiometricResult::Cancelled);
711
        assert_eq!(mgr.in_flight, 2);
712
        assert!(mgr.has_pending_async());
713
        mgr.set_last_result(BiometricResult::Failed);
714
        assert_eq!(mgr.in_flight, 1);
715
        assert!(mgr.has_pending_async());
716
        mgr.set_last_result(BiometricResult::Authenticated);
717
        assert_eq!(mgr.in_flight, 0);
718
        assert!(!mgr.has_pending_async(), "all three outcomes folded back");
719

            
720
        // Even from a saturated count, one completion retires exactly one.
721
        let mut mgr = BiometricManager::new();
722
        mgr.mark_requests_dispatched(u32::MAX);
723
        mgr.set_last_result(BiometricResult::Error);
724
        assert_eq!(mgr.in_flight, u32::MAX - 1);
725
    }
726

            
727
    #[test]
728
    fn has_pending_async_is_true_exactly_while_in_flight_is_non_zero() {
729
        for n in [0u32, 1, 2, u32::MAX - 1, u32::MAX] {
730
            let mut mgr = BiometricManager::new();
731
            mgr.mark_requests_dispatched(n);
732
            assert_eq!(
733
                mgr.has_pending_async(),
734
                n > 0,
735
                "has_pending_async disagreed with in_flight = {n}"
736
            );
737
        }
738
    }
739

            
740
    // ── clear_pending_event ────────────────────────────────────────────
741

            
742
    #[test]
743
    fn clear_pending_event_is_idempotent_and_touches_nothing_else() {
744
        let mut mgr = BiometricManager::new();
745
        mgr.set_availability(BiometricKind::Face);
746
        mgr.mark_requests_dispatched(2);
747
        mgr.set_last_result(BiometricResult::Authenticated);
748
        assert!(mgr.pending_event);
749

            
750
        mgr.clear_pending_event();
751
        assert!(!mgr.pending_event);
752
        let after_first = mgr;
753

            
754
        // Clearing twice (a second event pass with no new outcome) is safe.
755
        mgr.clear_pending_event();
756
        assert_eq!(mgr, after_first, "the second clear is a no-op");
757
        assert!(mgr.get_pending_events(ts()).is_empty());
758

            
759
        // The outcome, the sensor probe and the in-flight count survive it.
760
        assert_eq!(mgr.last_result(), Some(BiometricResult::Authenticated));
761
        assert!(
762
            mgr.last_was_success(),
763
            "clearing the event must not re-lock the vault"
764
        );
765
        assert_eq!(mgr.availability(), BiometricKind::Face);
766
        assert_eq!(mgr.in_flight, 1);
767
        assert!(
768
            mgr.has_pending_async(),
769
            "the second prompt is still outstanding"
770
        );
771
    }
772

            
773
    #[test]
774
    fn clear_pending_event_on_a_fresh_manager_is_a_no_op() {
775
        let mut mgr = BiometricManager::new();
776
        mgr.clear_pending_event();
777
        assert_eq!(mgr, BiometricManager::new());
778
    }
779

            
780
    // ── EventProvider ──────────────────────────────────────────────────
781

            
782
    #[test]
783
    fn pending_event_yields_exactly_one_root_event_and_is_not_consuming() {
784
        let mut mgr = BiometricManager::new();
785
        mgr.set_last_result(BiometricResult::Authenticated);
786

            
787
        let events = mgr.get_pending_events(ts());
788
        assert_eq!(events.len(), 1);
789
        assert_eq!(events[0].event_type, EventType::BiometricResult);
790
        assert_eq!(events[0].source, CoreEventSource::User);
791
        assert_eq!(
792
            events[0].target,
793
            DomNodeId::ROOT,
794
            "the outcome is window-level, not node-level"
795
        );
796
        assert_eq!(events[0].data, EventData::None);
797
        assert_eq!(
798
            events[0].timestamp,
799
            ts(),
800
            "the caller's timestamp is preserved"
801
        );
802

            
803
        // Reading is not draining — only clear_pending_event() retires it.
804
        assert_eq!(mgr.get_pending_events(ts()).len(), 1);
805
        mgr.clear_pending_event();
806
        assert!(mgr.get_pending_events(ts()).is_empty());
807
    }
808

            
809
    // ── Copy semantics ─────────────────────────────────────────────────
810

            
811
    #[test]
812
    fn manager_is_copy_so_a_snapshot_never_sees_later_mutations() {
813
        // `BiometricManager: Copy` — a caller holding `let mut m = *mgr;`
814
        // mutates a detached snapshot. Pin the semantics so a future field
815
        // (e.g. a Vec of pending prompts) can't silently change them.
816
        let mut original = BiometricManager::new();
817
        original.mark_requests_dispatched(1);
818

            
819
        let mut snapshot = original;
820
        snapshot.set_last_result(BiometricResult::Authenticated);
821
        snapshot.set_availability(BiometricKind::Iris);
822

            
823
        assert_eq!(original.last_result(), None, "the original is untouched");
824
        assert_eq!(original.availability(), BiometricKind::NotAvailable);
825
        assert_eq!(original.in_flight, 1);
826
        assert!(!original.pending_event);
827

            
828
        assert_eq!(snapshot.last_result(), Some(BiometricResult::Authenticated));
829
        assert_eq!(snapshot.in_flight, 0);
830
    }
831

            
832
    // ── async result channel ───────────────────────────────────────────
833

            
834
    #[test]
835
    fn results_channel_round_trips_every_variant_in_arrival_order() {
836
        let _guard = lock_channels();
837
        drop(drain_biometric_results());
838

            
839
        for result in ALL_RESULTS {
840
            push_biometric_result(result);
841
        }
842
        let drained = drain_biometric_results();
843
        assert_eq!(drained.len(), ALL_RESULTS.len(), "no result is dropped");
844
        assert_eq!(
845
            drained.as_slice(),
846
            ALL_RESULTS.as_slice(),
847
            "the channel is FIFO — the layout pass relies on last-one-wins"
848
        );
849
        assert!(
850
            drain_biometric_results().is_empty(),
851
            "draining takes the queue, it does not copy it"
852
        );
853
    }
854

            
855
    #[test]
856
    fn draining_an_empty_results_channel_repeatedly_is_safe() {
857
        let _guard = lock_channels();
858
        drop(drain_biometric_results());
859
        for _ in 0..3 {
860
            assert!(drain_biometric_results().is_empty());
861
        }
862
    }
863

            
864
    #[test]
865
    fn duplicate_results_are_all_preserved_in_the_channel() {
866
        // Dedup is the manager's job (via the change flag), not the
867
        // channel's — every parked outcome answers its own prompt.
868
        let _guard = lock_channels();
869
        drop(drain_biometric_results());
870

            
871
        for _ in 0..64 {
872
            push_biometric_result(BiometricResult::Failed);
873
        }
874
        let drained = drain_biometric_results();
875
        assert_eq!(drained.len(), 64);
876
        assert!(drained.iter().all(|r| *r == BiometricResult::Failed));
877

            
878
        // Folding them all back never underflows in_flight, and the last
879
        // one still wins.
880
        let mut mgr = BiometricManager::new();
881
        mgr.mark_requests_dispatched(2);
882
        for r in &drained {
883
            mgr.set_last_result(*r);
884
        }
885
        assert_eq!(mgr.in_flight, 0, "saturating_sub floors at zero");
886
        assert_eq!(mgr.last_result(), Some(BiometricResult::Failed));
887
    }
888

            
889
    #[test]
890
    fn results_pushed_from_many_threads_are_all_delivered() {
891
        let _guard = lock_channels();
892
        drop(drain_biometric_results());
893

            
894
        let threads: Vec<_> = (0..4)
895
            .map(|_| {
896
                std::thread::spawn(|| {
897
                    for _ in 0..25 {
898
                        push_biometric_result(BiometricResult::Authenticated);
899
                    }
900
                })
901
            })
902
            .collect();
903
        for t in threads {
904
            t.join()
905
                .expect("a backend thread panicked while parking a result");
906
        }
907

            
908
        let drained = drain_biometric_results();
909
        assert_eq!(
910
            drained.len(),
911
            100,
912
            "no result lost across 4 backend threads"
913
        );
914
        assert!(drained.iter().all(|r| r.is_success()));
915
        assert!(drain_biometric_results().is_empty());
916
    }
917

            
918
    // ── request channel ────────────────────────────────────────────────
919

            
920
    #[test]
921
    fn has_queued_requests_tracks_the_queue_exactly() {
922
        let _guard = lock_channels();
923
        drop(drain_biometric_requests());
924
        assert!(
925
            !has_queued_requests(),
926
            "known-false: nothing parked after a drain"
927
        );
928

            
929
        push_biometric_request(BiometricPrompt::new("Unlock".into()));
930
        assert!(has_queued_requests(), "known-true: one prompt parked");
931
        // Reading the flag must not consume the queue.
932
        assert!(has_queued_requests());
933

            
934
        push_biometric_request(BiometricPrompt::default());
935
        assert!(has_queued_requests());
936

            
937
        let drained = drain_biometric_requests();
938
        assert_eq!(drained.len(), 2);
939
        assert!(
940
            !has_queued_requests(),
941
            "the pump's arming check must go quiet once the prompts are dispatched"
942
        );
943
    }
944

            
945
    #[test]
946
    fn request_channel_round_trips_hostile_prompt_strings_byte_for_byte() {
947
        let _guard = lock_channels();
948
        drop(drain_biometric_requests());
949

            
950
        let hostile: Vec<String> = alloc::vec![
951
            String::new(),                           // empty → platform default
952
            "Entsperre den Tresor 🔐".to_string(),   // emoji (4-byte scalar)
953
            "افتح الخزنة".to_string(),               // RTL
954
            "e\u{0301}\u{0301}\u{0301}".to_string(), // stacked combining marks
955
            "line\nbreak\ttab\r\n".to_string(),      // control chars
956
            "nul\0inside".to_string(),               // interior NUL
957
            "%s %n {} \\0 ${x}".to_string(),         // format-string bait
958
            "u".repeat(64 * 1024),                   // 64 KiB reason
959
        ];
960

            
961
        for reason in &hostile {
962
            push_biometric_request(BiometricPrompt {
963
                reason: reason.clone().into(),
964
                cancel_label: reason.clone().into(),
965
                allow_device_credential: true,
966
            });
967
        }
968

            
969
        let drained = drain_biometric_requests();
970
        assert_eq!(drained.len(), hostile.len(), "no prompt is dropped");
971
        for (prompt, expected) in drained.iter().zip(hostile.iter()) {
972
            assert_eq!(
973
                prompt.reason.as_str(),
974
                expected.as_str(),
975
                "the reason must survive the channel unmangled"
976
            );
977
            assert_eq!(prompt.cancel_label.as_str(), expected.as_str());
978
            assert!(prompt.allow_device_credential);
979
        }
980
        assert_eq!(
981
            drained.last().unwrap().reason.as_str().len(),
982
            64 * 1024,
983
            "a 64 KiB reason is not truncated"
984
        );
985
        assert!(!has_queued_requests());
986
    }
987

            
988
    #[test]
989
    fn requests_pushed_from_many_threads_are_all_delivered() {
990
        let _guard = lock_channels();
991
        drop(drain_biometric_requests());
992

            
993
        let threads: Vec<_> = (0..4)
994
            .map(|i| {
995
                std::thread::spawn(move || {
996
                    for j in 0..25 {
997
                        push_biometric_request(BiometricPrompt::new(
998
                            alloc::format!("t{i}-{j}").into(),
999
                        ));
                    }
                })
            })
            .collect();
        for t in threads {
            t.join()
                .expect("a callback thread panicked while queueing a prompt");
        }
        let drained = drain_biometric_requests();
        assert_eq!(
            drained.len(),
            100,
            "no prompt lost across 4 callback threads"
        );
        // Each thread's own prompts keep their relative order.
        for i in 0..4 {
            let mine: Vec<_> = drained
                .iter()
                .filter(|p| p.reason.as_str().starts_with(&alloc::format!("t{i}-")))
                .collect();
            assert_eq!(mine.len(), 25, "thread {i} lost a prompt");
            for (j, p) in mine.iter().enumerate() {
                assert_eq!(p.reason.as_str(), alloc::format!("t{i}-{j}"));
            }
        }
        assert!(!has_queued_requests());
    }
    // ── full request → dispatch → result loop ──────────────────────────
    #[test]
    fn full_request_dispatch_result_loop_leaves_the_pump_disarmed() {
        let _guard = lock_channels();
        drop(drain_biometric_requests());
        drop(drain_biometric_results());
        let mut mgr = BiometricManager::new();
        mgr.set_availability(BiometricKind::Fingerprint);
        // 1. Two callbacks each queue a prompt.
        push_biometric_request(BiometricPrompt::new("Unlock A".into()));
        push_biometric_request(BiometricPrompt::new("Unlock B".into()));
        assert!(
            has_queued_requests(),
            "queued-but-undispatched prompts must arm the pump on their own — has_pending_async() \
             cannot see them yet"
        );
        assert!(!mgr.has_pending_async());
        // 2. The layout pass drains and dispatches them.
        let requests = drain_biometric_requests();
        assert_eq!(requests.len(), 2);
        mgr.mark_requests_dispatched(u32::try_from(requests.len()).unwrap());
        assert!(!has_queued_requests());
        assert!(
            mgr.has_pending_async(),
            "now the in-flight count arms the pump"
        );
        // 3. The backend parks both outcomes; the next pass folds them back.
        push_biometric_result(BiometricResult::Failed);
        push_biometric_result(BiometricResult::FellBackToPasscode);
        for r in drain_biometric_results() {
            mgr.set_last_result(r);
        }
        assert_eq!(mgr.in_flight, 0);
        assert!(
            !mgr.has_pending_async(),
            "pump disarms once every outcome folded"
        );
        assert!(mgr.pending_event);
        assert_eq!(mgr.get_pending_events(ts()).len(), 1);
        assert_eq!(mgr.last_result(), Some(BiometricResult::FellBackToPasscode));
        assert!(
            mgr.last_was_success(),
            "the passcode fallback unlocks the vault"
        );
        mgr.clear_pending_event();
        assert!(mgr.get_pending_events(ts()).is_empty());
    }
}