Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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]

Expand Down
8 changes: 8 additions & 0 deletions credentialsd-common/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Transport>),

ErrorInternal,
ErrorTimedOut,
ErrorCancelled,
Expand Down Expand Up @@ -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 {}
Expand Down
24 changes: 21 additions & 3 deletions credentialsd-ui/src/dbus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Transport>,
_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,
Expand Down
111 changes: 111 additions & 0 deletions credentialsd-ui/src/gui/view_model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub(crate) struct ViewModel {

// Transports offered to the user, e.g. USB and hybrid
transports: Vec<Transport>,
// Transports that gave up for this request, kept out of later updates
stopped_transports: Vec<Transport>,
selected_device: Option<Device>,

hybrid_qr_code_data: Option<Vec<u8>>,
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -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<Transport>) {
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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<Transport>,
) -> (Sender<BackgroundEvent>, Receiver<ViewUpdate>) {
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<ViewUpdate>) -> Vec<Transport> {
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]
);
});
}
}
152 changes: 152 additions & 0 deletions credentialsd/src/credential_service/bluetooth.rs
Original file line number Diff line number Diff line change
@@ -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<OwnedObjectPath, HashMap<String, HashMap<String, OwnedValue>>>;

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<ManagedObjects> {
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<bool>)]) -> 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);
}
}
Loading