From 6e08d5cd3c26761c852bcd8071be499b1163b436 Mon Sep 17 00:00:00 2001 From: K Panuragh Date: Tue, 17 Nov 2026 12:22:12 +0530 Subject: [PATCH] daemon: Offer hybrid once Bluetooth is turned on during a request libwebauthn reports Bluetooth as available whenever an adapter exists, even while it is powered off, and the transports were only detected once at the start of a request. So with Bluetooth off, the QR code option was offered but could not work, and turning Bluetooth on did not help. - Ask BlueZ whether an adapter is powered on, and only offer hybrid then. The check gives up after 1 s and doesn't start BlueZ if it isn't running. - If hybrid was not offered when discovery starts, check BlueZ every 2 s while it has an adapter that is turned off. Once one is turned on, add hybrid to the request's transports, send the UI the new list (new NotifyTransportsChanged UI control method) and start hybrid discovery. This happens at most once per request. - The UI keeps transports that gave up earlier in the request hidden when it gets a new list. Closes #206 --- CHANGELOG.md | 2 + credentialsd-common/src/model.rs | 8 + credentialsd-ui/src/dbus.rs | 24 +- credentialsd-ui/src/gui/view_model/mod.rs | 111 ++++++ .../src/credential_service/bluetooth.rs | 152 ++++++++ credentialsd/src/credential_service/mod.rs | 325 ++++++++++++++++-- credentialsd/src/dbus/ui_control.rs | 26 +- 7 files changed, 615 insertions(+), 33 deletions(-) create mode 100644 credentialsd/src/credential_service/bluetooth.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 06c48f6e..ee0a903f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Renamed the `username` field of `Credential` to `display_name`, matching WebAuthn's `user.displayName`. - `CreateSession` takes the list of available transports (`as`) instead of placeholder devices (`a(ss)`). - daemon/ui: Add `TransportUnavailable` restart reason, sent when a transport stops after repeated failures; the UI then stops offering it. +- Added `NotifyTransportsChanged`, sent with the full transport list when the transports offered to the user change during a request. ## Improvements @@ -18,6 +19,7 @@ - daemon: Allow clients to cancel requests through xdg-desktop-portal. - ui: Pass the caller's activation token to the compositor when showing the dialog, so it can take focus when the requesting window is in the background (#152) - ui: Disable core dumps for the UI process, which handles typed PINs. Build with `-Denable_core_dumps=true` to allow them for debugging (#209) +- daemon: Only offer hybrid (QR code) when a Bluetooth adapter is powered on, and offer it as soon as Bluetooth is turned on during a request (#206) # 0.4.0 [2026-11-05] diff --git a/credentialsd-common/src/model.rs b/credentialsd-common/src/model.rs index 0f0e3e41..b2e06fe8 100644 --- a/credentialsd-common/src/model.rs +++ b/credentialsd-common/src/model.rs @@ -63,6 +63,10 @@ pub enum BackgroundEvent { reason: TransportRestartReason, }, + /// The transports offered to the user changed during the request, e.g. + /// because the user turned Bluetooth on. Contains the full new list. + TransportsChanged(Vec), + ErrorInternal, ErrorTimedOut, ErrorCancelled, @@ -165,6 +169,10 @@ pub struct NotifyHybridConnectedOptions {} #[zvariant(signature = "dict")] pub struct NotifyNfcConnectedOptions {} +#[derive(Debug, SerializeDict, DeserializeDict, Type)] +#[zvariant(signature = "dict")] +pub struct NotifyTransportsChangedOptions {} + #[derive(Debug, SerializeDict, DeserializeDict, Type)] #[zvariant(signature = "dict")] pub struct NotifyUsbConnectedOptions {} diff --git a/credentialsd-ui/src/dbus.rs b/credentialsd-ui/src/dbus.rs index 8c3721ac..32246251 100644 --- a/credentialsd-ui/src/dbus.rs +++ b/credentialsd-ui/src/dbus.rs @@ -30,9 +30,9 @@ use credentialsd_common::model::{ NotifyHybridConnectingOptions, NotifyHybridRestartingOptions, NotifyHybridStartedOptions, NotifyNeedsPinOptions, NotifyNeedsUserPresenceOptions, NotifyNeedsUserVerificationOptions, NotifyNfcConnectedOptions, NotifyNfcRestartingOptions, NotifyPinNotSetOptions, - NotifySelectingCredentialOptions, NotifyUsbConnectedOptions, NotifyUsbRestartingOptions, - Operation, PinNotSetError, PortalBackendOptions, SetDevicePinOptions, Transport, - TransportRestartReason, UserInteractedEvent, WindowHandle, + NotifySelectingCredentialOptions, NotifyTransportsChangedOptions, NotifyUsbConnectedOptions, + NotifyUsbRestartingOptions, Operation, PinNotSetError, PortalBackendOptions, + SetDevicePinOptions, Transport, TransportRestartReason, UserInteractedEvent, WindowHandle, }; use crate::{RequestingApplication, ViewRequest, client::FlowControlClient}; @@ -285,6 +285,24 @@ impl CredentialPortalBackend { .await } + /// Called when the transports offered to the user change during the + /// request, e.g. because Bluetooth was turned on. `transports` is the full + /// new list. + async fn notify_transports_changed( + &self, + #[zbus(object_server)] object_server: &ObjectServer, + session_handle: ObjectPath<'_>, + transports: Vec, + _options: NotifyTransportsChangedOptions, + ) -> fdo::Result<()> { + self.notify_state_changed( + object_server, + session_handle, + BackgroundEvent::TransportsChanged(transports), + ) + .await + } + /// Called when a NFC authenticator has connected. async fn notify_nfc_connected( &self, diff --git a/credentialsd-ui/src/gui/view_model/mod.rs b/credentialsd-ui/src/gui/view_model/mod.rs index 959727f0..28be4afc 100644 --- a/credentialsd-ui/src/gui/view_model/mod.rs +++ b/credentialsd-ui/src/gui/view_model/mod.rs @@ -33,6 +33,8 @@ pub(crate) struct ViewModel { // Transports offered to the user, e.g. USB and hybrid transports: Vec, + // Transports that gave up for this request, kept out of later updates + stopped_transports: Vec, selected_device: Option, hybrid_qr_code_data: Option>, @@ -64,6 +66,7 @@ impl ViewModel { title: String::default(), subtitle: String::default(), transports, + stopped_transports: Vec::new(), selected_device: None, hybrid_qr_code_data: None, } @@ -128,8 +131,19 @@ impl ViewModel { .unwrap(); } + /// Offers the transports the daemon now reports, e.g. hybrid once Bluetooth + /// was turned on, except those that gave up earlier in this request. + async fn set_transports(&mut self, transports: Vec) { + self.transports = transports + .into_iter() + .filter(|transport| !self.stopped_transports.contains(transport)) + .collect(); + self.send_transports().await; + } + /// Stops offering transports that gave up for this request. async fn drop_transports(&mut self, gone: &[Transport]) { + self.stopped_transports.extend_from_slice(gone); self.transports .retain(|transport| !gone.contains(transport)); self.send_transports().await; @@ -338,6 +352,10 @@ impl ViewModel { .await .unwrap(); } + Event::Background(BackgroundEvent::TransportsChanged(transports)) => { + info!("Available transports changed: {transports:?}"); + self.set_transports(transports).await; + } // A transport gave up for this request: stop offering it. No // TransportRestarting here, as that would pull the user off the page // of a transport that still works. @@ -423,3 +441,96 @@ pub enum Event { Background(BackgroundEvent), View(ViewEvent), } + +#[cfg(test)] +mod tests { + use async_std::channel::unbounded; + + use super::*; + + /// Starts a view model offering `transports`, and returns the channel to + /// send it daemon events and the channel it sends view updates to. + fn start_view_model( + transports: Vec, + ) -> (Sender, Receiver) { + let (_view_tx, view_rx) = unbounded(); + let (bg_tx, bg_rx) = unbounded(); + let (update_tx, updates) = unbounded(); + let (client_tx, _sent) = unbounded(); + let client = FlowControlClient { + tx: client_tx, + rx: AsyncMutex::new(Some(bg_rx)), + }; + let request = ViewRequest { + operation: Operation::PublicKeyCreate, + rp_id: "example.com".to_string(), + requesting_app: RequestingApplication::default(), + initial_transports: transports, + window_handle: None, + activation_token: None, + }; + let mut vm = ViewModel::new( + request, + Arc::new(AsyncMutex::new(client)), + view_rx, + update_tx, + ); + async_std::task::spawn(async move { vm.start_event_loop().await }); + (bg_tx, updates) + } + + async fn next_transports(updates: &Receiver) -> Vec { + match updates.recv().await.unwrap() { + ViewUpdate::SetTransports(transports) => transports, + other => panic!("expected SetTransports, got {other:?}"), + } + } + + #[test] + fn transport_list_follows_daemon_updates() { + async_std::task::block_on(async { + let (bg_tx, updates) = start_view_model(vec![Transport::Usb]); + + bg_tx + .send(BackgroundEvent::TransportsChanged(vec![ + Transport::Usb, + Transport::HybridQr, + ])) + .await + .unwrap(); + + assert_eq!( + next_transports(&updates).await, + [Transport::Usb, Transport::HybridQr] + ); + }); + } + + #[test] + fn stopped_transport_stays_hidden_after_daemon_update() { + async_std::task::block_on(async { + let (bg_tx, updates) = start_view_model(vec![Transport::Usb, Transport::Nfc]); + + bg_tx + .send(BackgroundEvent::UsbRestarting { + reason: TransportRestartReason::TransportUnavailable, + }) + .await + .unwrap(); + assert_eq!(next_transports(&updates).await, [Transport::Nfc]); + + bg_tx + .send(BackgroundEvent::TransportsChanged(vec![ + Transport::Usb, + Transport::Nfc, + Transport::HybridQr, + ])) + .await + .unwrap(); + assert_eq!( + next_transports(&updates).await, + [Transport::Nfc, Transport::HybridQr] + ); + }); + } +} diff --git a/credentialsd/src/credential_service/bluetooth.rs b/credentialsd/src/credential_service/bluetooth.rs new file mode 100644 index 00000000..ae01ee45 --- /dev/null +++ b/credentialsd/src/credential_service/bluetooth.rs @@ -0,0 +1,152 @@ +//! Checks whether Bluetooth is actually usable, i.e. an adapter is powered on. +//! +//! libwebauthn only checks that an adapter exists, but BlueZ keeps adapters +//! around while Bluetooth is turned off. + +use std::{collections::HashMap, time::Duration}; + +use zbus::{ + proxy::MethodFlags, + zvariant::{OwnedObjectPath, OwnedValue}, +}; + +type ManagedObjects = HashMap>>; + +const ADAPTER_INTERFACE: &str = "org.bluez.Adapter1"; + +/// How long to wait for BlueZ before treating Bluetooth as unavailable, so a +/// stuck bluetoothd can't hold up a request. +const BLUEZ_TIMEOUT: Duration = Duration::from_secs(1); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BluetoothState { + /// At least one adapter is powered on. + Powered, + /// BlueZ has adapters, but none is powered on. + Off, + /// BlueZ isn't running, didn't answer in time, or has no adapters. + Unavailable, +} + +/// Asks BlueZ whether an adapter is powered on. +/// +/// libwebauthn uses the first adapter btleplug reports, so on a machine with +/// several adapters, hybrid can still fail if that one is the one turned off. +pub(crate) async fn bluetooth_state() -> BluetoothState { + match tokio::time::timeout(BLUEZ_TIMEOUT, managed_objects()).await { + Ok(Ok(objects)) => adapter_state(&objects), + Ok(Err(err)) => { + tracing::debug!(%err, "Could not query BlueZ adapters"); + BluetoothState::Unavailable + } + Err(_) => { + tracing::debug!("BlueZ did not answer in time"); + BluetoothState::Unavailable + } + } +} + +/// Uses a new system bus connection for each check: they only happen at the +/// start of a request and every few seconds while a request waits for +/// Bluetooth, and a cached connection would be tied to the async runtime that +/// created it. +/// +/// Doesn't start BlueZ if it isn't running. +async fn managed_objects() -> zbus::Result { + let connection = zbus::Connection::system().await?; + let proxy = zbus::Proxy::new( + &connection, + "org.bluez", + "/", + "org.freedesktop.DBus.ObjectManager", + ) + .await?; + proxy + .call_with_flags("GetManagedObjects", MethodFlags::NoAutoStart.into(), &()) + .await? + .ok_or_else(|| zbus::Error::Failure("No reply from BlueZ".to_string())) +} + +fn adapter_state(objects: &ManagedObjects) -> BluetoothState { + let mut adapters = objects + .values() + .filter_map(|interfaces| interfaces.get(ADAPTER_INTERFACE)) + .peekable(); + if adapters.peek().is_none() { + return BluetoothState::Unavailable; + } + let powered = adapters + .filter_map(|props| props.get("Powered")) + .any(|powered| matches!(**powered, zbus::zvariant::Value::Bool(true))); + if powered { + BluetoothState::Powered + } else { + BluetoothState::Off + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn objects(adapters: &[(&str, Option)]) -> ManagedObjects { + adapters + .iter() + .map(|(path, powered)| { + let mut props = HashMap::new(); + if let Some(powered) = powered { + props.insert("Powered".to_string(), OwnedValue::from(*powered)); + } + let interfaces = HashMap::from([("org.bluez.Adapter1".to_string(), props)]); + (OwnedObjectPath::try_from(*path).unwrap(), interfaces) + }) + .collect() + } + + #[test] + fn powered_adapter_is_usable() { + assert_eq!( + adapter_state(&objects(&[("/org/bluez/hci0", Some(true))])), + BluetoothState::Powered + ); + } + + #[test] + fn powered_off_adapter_is_off() { + assert_eq!( + adapter_state(&objects(&[("/org/bluez/hci0", Some(false))])), + BluetoothState::Off + ); + assert_eq!( + adapter_state(&objects(&[("/org/bluez/hci0", None)])), + BluetoothState::Off + ); + } + + #[test] + fn no_adapter_is_unavailable() { + assert_eq!(adapter_state(&HashMap::new()), BluetoothState::Unavailable); + } + + #[test] + fn any_powered_adapter_is_enough() { + assert_eq!( + adapter_state(&objects(&[ + ("/org/bluez/hci0", Some(false)), + ("/org/bluez/hci1", Some(true)), + ])), + BluetoothState::Powered + ); + } + + #[test] + fn other_interfaces_are_ignored() { + let mut objects = objects(&[]); + let props = HashMap::from([("Powered".to_string(), OwnedValue::from(true))]); + objects.insert( + OwnedObjectPath::try_from("/org/bluez/hci0/dev_00").unwrap(), + HashMap::from([("org.bluez.Device1".to_string(), props)]), + ); + assert_eq!(adapter_state(&objects), BluetoothState::Unavailable); + } +} diff --git a/credentialsd/src/credential_service/mod.rs b/credentialsd/src/credential_service/mod.rs index d0ed9e68..8a7eda51 100644 --- a/credentialsd/src/credential_service/mod.rs +++ b/credentialsd/src/credential_service/mod.rs @@ -1,3 +1,4 @@ +pub mod bluetooth; pub mod hybrid; pub mod nfc; pub mod usb; @@ -7,6 +8,7 @@ use std::{ pin::Pin, sync::{Arc, Mutex, OnceLock}, task::Poll, + time::Duration, }; use async_trait::async_trait; @@ -32,6 +34,7 @@ use crate::{ }; use self::{ + bluetooth::BluetoothState, hybrid::{HybridHandler, HybridState, HybridStateInternal}, usb::{UsbHandler, UsbStateInternal}, }; @@ -170,7 +173,9 @@ pub struct CredentialService { /// Current request and channel to respond to caller. ctx: Arc>>, - hybrid_handler: Mutex, + /// Shared so hybrid discovery can be started later in a request, once + /// Bluetooth becomes available. + hybrid_handler: Arc>, nfc_handler: Mutex, usb_handler: Mutex, } @@ -182,7 +187,7 @@ impl Self { ctx: Arc::new(Mutex::new(None)), - hybrid_handler: Mutex::new(hybrid_handler), + hybrid_handler: Arc::new(Mutex::new(hybrid_handler)), nfc_handler: Mutex::new(nfc_handler), usb_handler: Mutex::new(usb_handler), } @@ -195,29 +200,15 @@ impl async fn get_hybrid_credential( &self, ) -> Pin + Send + 'static>> { - let guard = self.ctx.lock().unwrap(); - if let Some(RequestContext { - ref request, - ref cancellation, - .. - }) = *guard - { - let stream = self - .hybrid_handler - .lock() - .unwrap() - .start(request, cancellation.clone()); - let ctx = self.ctx.clone(); - Box::pin(HybridStateStream { - inner: stream, - ctx, - cancellation_token: cancellation.clone(), - }) - } else { - tracing::error!( - "Attempted to start hybrid credential flow, but no request context was found." - ); - todo!("Handle error when context is not set up.") + let request_id = self.ctx.lock().unwrap().as_ref().map(|ctx| ctx.request_id); + match request_id.and_then(|id| start_hybrid(&self.hybrid_handler, &self.ctx, id)) { + Some(stream) => stream, + None => { + tracing::error!( + "Attempted to start hybrid credential flow, but no request context was found." + ); + todo!("Handle error when context is not set up.") + } } } @@ -277,7 +268,7 @@ impl } #[async_trait] -impl ManageDevice +impl ManageDevice for CredentialService { async fn init_request( @@ -285,7 +276,7 @@ impl Manage request: &CredentialRequest, tx: oneshot::Sender>, ) -> Result<(RequestId, CancellationToken), CredentialServiceError> { - let supported_transports = supported_transports(&available_transports().await); + let supported_transports = supported_transports(&usable_transports().await); let mut cred_request = self.ctx.lock().unwrap(); if cred_request.is_some() { Err(CredentialServiceError::Internal( @@ -362,6 +353,25 @@ impl Manage .map(DeviceStateUpdate::from) .boxed(); selected_transports.push(hybrid); + } else if let Some((request_id, cancellation)) = self + .ctx + .lock() + .unwrap() + .as_ref() + .map(|ctx| (ctx.request_id, ctx.cancellation.clone())) + { + // Hybrid wasn't offered because Bluetooth was off. Offer and start it + // as soon as the user turns Bluetooth on. + let handler = self.hybrid_handler.clone(); + let ctx = self.ctx.clone(); + let watch = hybrid_when_available( + bluetooth::bluetooth_state, + TRANSPORT_POLL_INTERVAL, + cancellation, + move || add_hybrid(&handler, &ctx, request_id), + ) + .boxed(); + selected_transports.push(watch); } futures::stream::select_all(selected_transports).boxed() } @@ -518,11 +528,16 @@ pub enum DeviceStateUpdate { Hybrid(HybridState), Nfc(NfcState), Usb(UsbState), + /// The transports offered to the user changed during the request. + TransportsChanged(Vec), } impl From for BackgroundEvent { fn from(value: DeviceStateUpdate) -> Self { match value { + DeviceStateUpdate::TransportsChanged(transports) => { + BackgroundEvent::TransportsChanged(transports) + } DeviceStateUpdate::Hybrid(state) => (&state).into(), DeviceStateUpdate::Nfc(state) => (&state).into(), DeviceStateUpdate::Usb(state) => (&state).into(), @@ -585,6 +600,124 @@ pub(super) fn is_ceremony_terminating(err: &CredentialServiceError) -> bool { } } +/// The transports that can be used right now: libwebauthn's list, without +/// the Bluetooth-based ones unless an adapter is powered on. +async fn usable_transports() -> Vec { + let transports = available_transports().await; + let powered = transports.contains(&libwebauthn::Transport::Hybrid) + && bluetooth::bluetooth_state().await == BluetoothState::Powered; + with_bluetooth_power(transports, powered) +} + +fn with_bluetooth_power( + mut transports: Vec, + powered: bool, +) -> Vec { + if !powered { + transports.retain(|t| { + !matches!( + t, + libwebauthn::Transport::Ble | libwebauthn::Transport::Hybrid + ) + }); + } + transports +} + +/// How often to check whether Bluetooth became available during a request. +const TRANSPORT_POLL_INTERVAL: Duration = Duration::from_secs(2); + +/// Starts hybrid discovery for request `request_id`, or returns `None` if that +/// request is no longer the current one. +fn start_hybrid( + handler: &Mutex, + ctx: &Arc>>, + request_id: RequestId, +) -> Option + Send + 'static>>> { + let guard = ctx.lock().unwrap(); + let RequestContext { + request, + cancellation, + .. + } = guard.as_ref().filter(|ctx| ctx.request_id == request_id)?; + let stream = handler.lock().unwrap().start(request, cancellation.clone()); + Some(Box::pin(HybridStateStream { + inner: stream, + ctx: ctx.clone(), + cancellation_token: cancellation.clone(), + })) +} + +type DeviceUpdateStream = Pin + Send + 'static>>; + +/// Adds hybrid to the transports of request `request_id` and starts it. +/// Returns the new transport list and the hybrid stream, or `None` if that +/// request is no longer the current one. +fn add_hybrid( + handler: &Mutex, + ctx: &Arc>>, + request_id: RequestId, +) -> Option<(Vec, DeviceUpdateStream)> { + let transports = { + let mut guard = ctx.lock().unwrap(); + let ctx = guard.as_mut().filter(|ctx| ctx.request_id == request_id)?; + if !ctx.transports.contains(&Transport::HybridQr) { + ctx.transports.push(Transport::HybridQr); + } + ctx.transports.clone() + }; + let hybrid = start_hybrid(handler, ctx, request_id)?; + Some((transports, hybrid.map(DeviceStateUpdate::from).boxed())) +} + +/// Waits for hybrid to become usable during a request, e.g. because the user +/// turned Bluetooth on, by calling `bluetooth_state` every `interval`. Once an +/// adapter is powered on, calls `start_hybrid`, yields the new transport list +/// and continues with the hybrid stream. +/// +/// Ends without yielding anything if `cancellation` fires first (the request +/// finished or was cancelled), if there is no Bluetooth to wait for (BlueZ +/// isn't running or has no adapter), or if `start_hybrid` returns `None`. +fn hybrid_when_available( + mut bluetooth_state: P, + interval: Duration, + cancellation: CancellationToken, + start_hybrid: impl FnOnce() -> Option<(Vec, S)> + Send + 'static, +) -> impl Stream + Send + 'static +where + P: FnMut() -> F + Send + 'static, + F: Future + Send, + S: Stream + Send + 'static, +{ + let wait_for_hybrid = async move { + let state = cancellation + .run_until_cancelled(async { + loop { + tokio::time::sleep(interval).await; + match bluetooth_state().await { + BluetoothState::Off => continue, + state => break state, + } + } + }) + .await?; + if state == BluetoothState::Unavailable { + tracing::debug!("No Bluetooth adapter to wait for, not offering hybrid"); + return None; + } + if cancellation.is_cancelled() { + return None; + } + let (transports, hybrid) = start_hybrid()?; + tracing::debug!("Bluetooth became available, starting hybrid discovery"); + let changed = DeviceStateUpdate::TransportsChanged(transports); + Some(futures_lite::stream::once(changed).chain(hybrid)) + }; + futures_lite::stream::once_future(wait_for_hybrid) + .filter_map(|stream| stream) + .flatten() +} + /// Maps the transports libwebauthn found to the ones this service runs. fn supported_transports(found: &[libwebauthn::Transport]) -> Vec { found @@ -758,6 +891,144 @@ mod tests { CredentialRequest::CreatePublicKeyCredentialRequest(make_credentials_request) } + #[test] + fn bluetooth_transports_are_dropped_when_powered_off() { + use libwebauthn::Transport::{Ble, Hybrid, Nfc, Usb}; + assert_eq!( + with_bluetooth_power(vec![Usb, Ble, Hybrid, Nfc], false), + [Usb, Nfc] + ); + assert_eq!( + with_bluetooth_power(vec![Usb, Ble, Hybrid], true), + [Usb, Ble, Hybrid] + ); + } + + const POLL: Duration = Duration::from_millis(5); + + /// A check that reports Bluetooth as off for the first `misses` calls, + /// then as `then`. + fn bluetooth_after( + misses: usize, + then: BluetoothState, + ) -> impl FnMut() -> std::future::Ready + Send + 'static { + let mut calls = 0; + move || { + calls += 1; + std::future::ready(if calls > misses { + then + } else { + BluetoothState::Off + }) + } + } + + type FakeHybrid = Option<( + Vec, + futures_lite::stream::Boxed, + )>; + + fn fake_hybrid() -> FakeHybrid { + Some(( + vec![Transport::Usb, Transport::HybridQr], + futures_lite::stream::once(DeviceStateUpdate::Hybrid(HybridState::Connecting)).boxed(), + )) + } + + #[tokio::test] + async fn hybrid_starts_when_bluetooth_becomes_available() { + let updates: Vec<_> = hybrid_when_available( + bluetooth_after(2, BluetoothState::Powered), + POLL, + CancellationToken::new(), + fake_hybrid, + ) + .collect() + .await; + + assert_eq!(updates.len(), 2); + let DeviceStateUpdate::TransportsChanged(transports) = &updates[0] else { + panic!("expected the new transport list first"); + }; + assert_eq!(transports, &[Transport::Usb, Transport::HybridQr]); + assert!(matches!( + updates[1], + DeviceStateUpdate::Hybrid(HybridState::Connecting) + )); + } + + #[tokio::test] + async fn bluetooth_watch_ends_when_request_ends() { + let cancellation = CancellationToken::new(); + let mut updates = hybrid_when_available( + bluetooth_after(usize::MAX, BluetoothState::Powered), + POLL, + cancellation.clone(), + || -> FakeHybrid { panic!("hybrid must not start") }, + ) + .boxed(); + tokio::time::sleep(POLL * 3).await; + cancellation.cancel(); + let next = tokio::time::timeout(Duration::from_secs(1), updates.next()).await; + assert!(matches!(next, Ok(None)), "stream should end once cancelled"); + } + + #[tokio::test] + async fn bluetooth_watch_ends_if_request_context_is_gone() { + let updates: Vec<_> = hybrid_when_available( + bluetooth_after(0, BluetoothState::Powered), + POLL, + CancellationToken::new(), + || -> FakeHybrid { None }, + ) + .collect() + .await; + assert!(updates.is_empty()); + } + + #[tokio::test] + async fn bluetooth_watch_ends_without_bluetooth() { + let updates: Vec<_> = hybrid_when_available( + bluetooth_after(1, BluetoothState::Unavailable), + POLL, + CancellationToken::new(), + || -> FakeHybrid { panic!("hybrid must not start") }, + ) + .collect() + .await; + assert!(updates.is_empty()); + } + + #[tokio::test] + async fn late_hybrid_start_only_applies_to_its_own_request() { + let service = CredentialService::new(MockHybridHandler, MockNfcHandler, MockUsbHandler); + let (tx, _rx) = oneshot::channel(); + let (request_id, _) = service + .init_request(&create_test_request().await, tx) + .await + .unwrap(); + // As if Bluetooth was off when the request started. + service.ctx.lock().unwrap().as_mut().unwrap().transports = vec![Transport::Usb]; + + assert!( + add_hybrid( + &service.hybrid_handler, + &service.ctx, + request_id.wrapping_add(1) + ) + .is_none() + ); + assert_eq!(service.get_transports(), [Transport::Usb]); + + let (transports, _) = + add_hybrid(&service.hybrid_handler, &service.ctx, request_id).unwrap(); + assert_eq!(transports, [Transport::Usb, Transport::HybridQr]); + assert_eq!(service.get_transports(), transports); + + service.cancel_request(request_id).await; + assert!(add_hybrid(&service.hybrid_handler, &service.ctx, request_id).is_none()); + } + #[tokio::test] async fn test_init_request_returns_token_and_id() { let service = CredentialService::new(MockHybridHandler, MockNfcHandler, MockUsbHandler); diff --git a/credentialsd/src/dbus/ui_control.rs b/credentialsd/src/dbus/ui_control.rs index d2fee9e5..0280e7ad 100644 --- a/credentialsd/src/dbus/ui_control.rs +++ b/credentialsd/src/dbus/ui_control.rs @@ -23,9 +23,9 @@ use credentialsd_common::model::{ NotifyHybridConnectingOptions, NotifyHybridRestartingOptions, NotifyHybridStartedOptions, NotifyNeedsPinOptions, NotifyNeedsUserPresenceOptions, NotifyNeedsUserVerificationOptions, NotifyNfcConnectedOptions, NotifyNfcRestartingOptions, NotifyPinNotSetOptions, - NotifySelectingCredentialOptions, NotifyUsbConnectedOptions, NotifyUsbRestartingOptions, - Operation, PinNotSetError, PortalBackendOptions, SetDevicePinOptions, Transport, - TransportRestartReason, UserInteractedEvent, WindowHandle, + NotifySelectingCredentialOptions, NotifyTransportsChangedOptions, NotifyUsbConnectedOptions, + NotifyUsbRestartingOptions, Operation, PinNotSetError, PortalBackendOptions, + SetDevicePinOptions, Transport, TransportRestartReason, UserInteractedEvent, WindowHandle, }; /// Used by the credential service to control the UI. @@ -134,6 +134,17 @@ trait UiControlService { _options: NotifyHybridConnectedOptions, ) -> fdo::Result<()>; + /// Called when the transports offered to the user change during the + /// request, e.g. because Bluetooth was turned on. `transports` is the full + /// new list. + #[zbus(no_reply)] + async fn notify_transports_changed( + &self, + session_handle: ObjectPath<'_>, + transports: Vec, + _options: NotifyTransportsChangedOptions, + ) -> fdo::Result<()>; + #[zbus(no_reply)] async fn notify_nfc_connected( &self, @@ -341,6 +352,15 @@ impl Ceremony { ) .await } + BackgroundEvent::TransportsChanged(transports) => { + self.proxy + .notify_transports_changed( + self.session_handle.as_ref(), + transports, + NotifyTransportsChangedOptions {}, + ) + .await + } BackgroundEvent::NfcRestarting { reason } => { self.proxy .notify_nfc_restarting(