diff --git a/CHANGELOG.md b/CHANGELOG.md index 61b63c1..3c52149 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - daemon: Show the UI through the backend that xdg-desktop-portal selects, passed in the new `ui_backend` option - daemon: Treat Debian's Firefox ESR (app ID `firefox-esr`) as a privileged client, like the other Firefox builds - daemon: Build the list of devices offered to the user from libwebauthn's `available_transports()`, the same source discovery uses (#32) +- 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) diff --git a/credentialsd/src/dbus/flow_control.rs b/credentialsd/src/dbus/flow_control.rs index 0446c61..7884395 100644 --- a/credentialsd/src/dbus/flow_control.rs +++ b/credentialsd/src/dbus/flow_control.rs @@ -17,6 +17,7 @@ use tokio::sync::mpsc::Receiver; use tokio::sync::oneshot; use tokio::sync::{Mutex as AsyncMutex, mpsc::Sender}; use tokio::task::AbortHandle; +use tokio_util::sync::CancellationToken; use zbus::connection::Connection; use zbus::names::OwnedWellKnownName; use zbus::zvariant::OwnedObjectPath; @@ -28,7 +29,9 @@ use crate::{ model::{CredentialRequest, CredentialResponse}, }; use crate::{ - credential_service::{CredentialServiceError, DeviceStateUpdate, ManageDevice, nfc::NfcState}, + credential_service::{ + CredentialServiceError, DeviceStateUpdate, ManageDevice, RequestId, nfc::NfcState, + }, model::ClientDetails, }; use crate::{dbus::ui_control::Ceremony, gateway::WebAuthnError}; @@ -36,9 +39,14 @@ use crate::{dbus::ui_control::Ceremony, gateway::WebAuthnError}; pub struct UiRequestContext { request: CredentialRequest, app: ClientDetails, + + /// Cancelled when the client closes the request before it completes. + client_cancellation: CancellationToken, + /// Client window handle window_handle: Option, activation_token: Option, + /// UI backend chosen by the portal frontend, or `None` for the default. ui_backend: Option, response_channel: oneshot::Sender>, @@ -59,6 +67,7 @@ pub async fn start_flow_control_service, activation_token: Option, + client_cancellation: CancellationToken, ) -> Result { + if client_cancellation.is_cancelled() { + return Err(CredentialServiceError::Internal( + "Request cancelled by client before it started.".to_string(), + )); + } let (request_tx, request_rx) = oneshot::channel(); let (request_id, cancellation_token) = svc.lock().await.init_request(&msg, request_tx).await?; let operation = msg.operation(); @@ -143,6 +159,26 @@ async fn handle>>> = Arc::new(Mutex::new(None)); let set_pin_tx: Arc>>> = Arc::new(Mutex::new(None)); @@ -296,6 +332,25 @@ async fn handle( + svc: &AsyncMutex, + request_id: RequestId, + request_cancellation: &CancellationToken, + client_cancellation: &CancellationToken, +) -> bool { + tokio::select! { + biased; + _ = request_cancellation.cancelled() => false, + _ = client_cancellation.cancelled() => { + tracing::debug!(%request_id, "Client closed the request, cancelling"); + svc.lock().await.cancel_request(request_id).await; + true + } + } +} + fn forward_background_event_stream( flow: Ceremony, mut stream: impl Stream + Send + Unpin + 'static, @@ -320,6 +375,7 @@ pub trait CredentialRequestController { &self, requesting_app: ClientDetails, request: CredentialRequest, + cancellation: CancellationToken, window_handle: Option, activation_token: Option, ui_backend: Option, @@ -336,6 +392,7 @@ impl CredentialRequestController for CredentialRequestControllerClient { &self, app: ClientDetails, request: CredentialRequest, + client_cancellation: CancellationToken, window_handle: Option, activation_token: Option, ui_backend: Option, @@ -345,6 +402,7 @@ impl CredentialRequestController for CredentialRequestControllerClient { .send(UiRequestContext { request, app, + client_cancellation, window_handle, activation_token, ui_backend, @@ -372,7 +430,6 @@ mod tests { use tokio_util::sync::CancellationToken; use super::*; - use crate::credential_service::RequestId; const TEST_REQUEST_ID: RequestId = 42; @@ -468,6 +525,7 @@ mod tests { app, None, None, + CancellationToken::new(), ) .await; @@ -477,4 +535,72 @@ mod tests { vec![TEST_REQUEST_ID] ); } + + #[tokio::test] + async fn test_client_cancellation_cancels_request() { + let svc = AsyncMutex::new(MockDeviceManager::default()); + let request_cancellation = CancellationToken::new(); + let client_cancellation = CancellationToken::new(); + client_cancellation.cancel(); + + let cancelled = cancel_on_client_request( + &svc, + TEST_REQUEST_ID, + &request_cancellation, + &client_cancellation, + ) + .await; + + assert!(cancelled); + assert_eq!( + *svc.lock().await.cancelled.lock().unwrap(), + vec![TEST_REQUEST_ID] + ); + } + + #[tokio::test] + async fn test_finished_request_is_not_cancelled_by_client() { + let svc = AsyncMutex::new(MockDeviceManager::default()); + let request_cancellation = CancellationToken::new(); + let client_cancellation = CancellationToken::new(); + request_cancellation.cancel(); + client_cancellation.cancel(); + + let cancelled = cancel_on_client_request( + &svc, + TEST_REQUEST_ID, + &request_cancellation, + &client_cancellation, + ) + .await; + + assert!(!cancelled); + assert!(svc.lock().await.cancelled.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn test_cancelled_client_request_does_not_start() { + let svc = Arc::new(AsyncMutex::new(MockDeviceManager::default())); + let app = ClientDetails { + app_id: "org.example.App".to_string(), + pid: 1, + }; + let client_cancellation = CancellationToken::new(); + client_cancellation.cancel(); + + let result = handle( + svc.clone(), + FailingUiController, + create_test_request().await, + app, + None, + None, + client_cancellation, + ) + .await; + + assert!(result.is_err()); + // The request was never initialized, so there is nothing to cancel. + assert!(svc.lock().await.cancelled.lock().unwrap().is_empty()); + } } diff --git a/credentialsd/src/gateway/dbus.rs b/credentialsd/src/gateway/dbus.rs index bc1dbb6..58f13a2 100644 --- a/credentialsd/src/gateway/dbus.rs +++ b/credentialsd/src/gateway/dbus.rs @@ -7,11 +7,12 @@ use std::{ use serde::{Deserialize, Serialize, ser::SerializeTuple}; use tokio::sync::Mutex as AsyncMutex; +use tokio_util::sync::CancellationToken; use zbus::{ - Connection, DBusError, interface, + Connection, DBusError, fdo, interface, message::Header, - names::{BusName, OwnedWellKnownName, UniqueName}, - zvariant::{DeserializeDict, Optional, Type, Value}, + names::{BusName, OwnedUniqueName, OwnedWellKnownName, UniqueName}, + zvariant::{DeserializeDict, Optional, OwnedObjectPath, Type, Value}, }; use credentialsd_common::model::WindowHandle; @@ -29,6 +30,9 @@ use super::{GatewayService, RequestContext, check_origin_from_app}; pub const PORTAL_SERVICE_PATH: &str = "/org/freedesktop/portal/desktop"; +/// Prefix of the request object paths created by xdg-desktop-portal. +const PORTAL_REQUEST_PATH_PREFIX: &str = "/org/freedesktop/portal/desktop/request/"; + pub(super) async fn start_dbus_gateway( svc: Arc>, ) -> Result { @@ -78,6 +82,7 @@ impl CredentialPortalGateway { activation_token, top_origin, public_key, + request_handle, ui_backend, } = options; @@ -118,21 +123,30 @@ impl CredentialPortalGateway { public_key: Some(CreatePublicKeyCredentialRequest { request_json }), }; - let response = self - .gateway_service - .lock() - .await - .handle_create_credential( - request, - context, - parent_window.into(), - activation_token, - ui_backend, - ) - .await - .map_err(Error::from); - - response.into() + run_ceremony( + connection, + header.sender(), + request_handle, + |cancellation| async move { + let Some(svc) = cancellation + .run_until_cancelled(self.gateway_service.lock()) + .await + else { + return Err(Error::AbortError); + }; + svc.handle_create_credential( + request, + context, + cancellation, + parent_window.into(), + activation_token, + ui_backend, + ) + .await + .map_err(Error::from) + }, + ) + .await } #[zbus(out_args("response", "results"))] @@ -149,6 +163,7 @@ impl CredentialPortalGateway { activation_token, top_origin, public_key, + request_handle, ui_backend, } = options; let app_validation_result = validate_app_details( @@ -185,20 +200,122 @@ impl CredentialPortalGateway { public_key: Some(GetPublicKeyCredentialRequest { request_json }), }; - let response = self - .gateway_service - .lock() - .await - .handle_get_credential( - request, - context, - parent_window.into(), - activation_token, - ui_backend, - ) - .await - .map_err(Error::from); - response.into() + run_ceremony( + connection, + header.sender(), + request_handle, + |cancellation| async move { + let Some(svc) = cancellation + .run_until_cancelled(self.gateway_service.lock()) + .await + else { + return Err(Error::AbortError); + }; + svc.handle_get_credential( + request, + context, + cancellation, + parent_window.into(), + activation_token, + ui_backend, + ) + .await + .map_err(Error::from) + }, + ) + .await + } +} + +/// Runs a ceremony that the client can cancel. +/// +/// If `request_handle` is set, an +/// `org.freedesktop.handler.portal.experimental.Request` object is exported at +/// that path for the duration of the ceremony. Calling `Close()` on it cancels +/// the token passed to `ceremony`, and the ceremony is reported as cancelled. +async fn run_ceremony( + connection: &Connection, + sender: Option<&UniqueName<'_>>, + request_handle: Option, + ceremony: F, +) -> PortalResult +where + F: FnOnce(CancellationToken) -> Fut, + Fut: Future>, +{ + let cancellation = CancellationToken::new(); + let Some(request_handle) = request_handle else { + return ceremony(cancellation).await.into(); + }; + + let Some(sender) = sender else { + return Err(Error::SecurityError).into(); + }; + if !request_handle + .as_str() + .starts_with(PORTAL_REQUEST_PATH_PREFIX) + { + tracing::warn!(%request_handle, "Invalid request handle passed. Rejecting request."); + return Err(Error::TypeError).into(); + } + let request = HandlerRequest { + caller: sender.to_owned().into(), + cancellation: cancellation.clone(), + }; + match connection + .object_server() + .at(request_handle.as_ref(), request) + .await + { + Ok(true) => {} + Ok(false) => { + tracing::warn!(%request_handle, "Request handle already in use. Rejecting request."); + return Err(Error::TypeError).into(); + } + Err(err) => return Err(Error::ZBus(err)).into(), + } + + let result = ceremony(cancellation.clone()).await; + + if let Err(err) = connection + .object_server() + .remove::(request_handle.as_ref()) + .await + { + tracing::warn!(%request_handle, %err, "Failed to remove request handle after ceremony completed"); + } + + if result.is_err() && cancellation.is_cancelled() { + tracing::debug!(%request_handle, "Request cancelled by client"); + PortalResult::cancelled() + } else { + result.into() + } +} + +/// Request object that lets the caller cancel an in-flight ceremony. +/// +/// This is part of the internal interface between xdg-desktop-portal and the +/// handler, not of the backend portal API: clients should close the +/// `org.freedesktop.portal.Request` object exported by xdg-desktop-portal, which +/// forwards the call here. +struct HandlerRequest { + /// Unique bus name of the caller that started the ceremony. + caller: OwnedUniqueName, + cancellation: CancellationToken, +} + +#[interface(name = "org.freedesktop.handler.portal.experimental.Request")] +impl HandlerRequest { + async fn close(&self, #[zbus(header)] header: Header<'_>) -> fdo::Result<()> { + if header.sender() != Some(&self.caller) { + tracing::warn!(sender = ?header.sender(), "Rejecting request to close request from untrusted caller"); + return Err(fdo::Error::AccessDenied( + "Only the caller that started the request may close it".to_string(), + )); + } + self.cancellation.cancel(); + Ok(()) } } @@ -232,6 +349,11 @@ struct CreateCredentialPortalOptions { /// type. public_key: Option, + /// Path at which to export an + /// `org.freedesktop.handler.portal.experimental.Request` + /// object that the caller can use to cancel the request. + request_handle: Option, + /// D-Bus name of the `org.freedesktop.impl.portal.experimental.Credential` /// backend to show the UI with, as chosen by the portal configuration. /// If omitted, the default UI is used. @@ -253,6 +375,11 @@ struct GetCredentialPortalOptions { /// type. public_key: Option, + /// Path at which to export an + /// `org.freedesktop.handler.portal.experimental.Request` + /// object that the caller can use to cancel the request. + request_handle: Option, + /// D-Bus name of the `org.freedesktop.impl.portal.experimental.Credential` /// backend to show the UI with, as chosen by the portal configuration. /// If omitted, the default UI is used. @@ -320,14 +447,21 @@ impl From for Error { #[derive(Serialize)] enum PortalResponse { Success = 0, - // Cancelled = 1, + Cancelled = 1, Other = 2, } #[derive(Type)] #[zvariant(signature = "ua{sv}")] struct PortalResult { - inner: Result, + /// `None` if the request was cancelled. + inner: Option>, +} + +impl PortalResult { + fn cancelled() -> Self { + PortalResult { inner: None } + } } impl Serialize for PortalResult @@ -341,14 +475,18 @@ where { let mut map = serializer.serialize_tuple(2)?; match &self.inner { - Err(err) => { + None => { + map.serialize_element(&(PortalResponse::Cancelled as u32))?; + map.serialize_element(&HashMap::<&str, Value<'_>>::new())?; + } + Some(Err(err)) => { map.serialize_element(&(PortalResponse::Other as u32))?; map.serialize_element(&HashMap::<&str, Value<'_>>::from([( "error", Value::Str(err.to_string().into()), )]))?; } - Ok(response) => { + Some(Ok(response)) => { map.serialize_element(&(PortalResponse::Success as u32))?; map.serialize_element(&response)?; } @@ -359,7 +497,7 @@ where impl From> for PortalResult { fn from(value: Result) -> Self { - PortalResult { inner: value } + PortalResult { inner: Some(value) } } } @@ -479,7 +617,233 @@ async fn query_peer_pidfd( #[cfg(test)] mod test { - use super::parse_ui_backend; + use std::{collections::HashMap, rc::Rc}; + + use gio::{TestDBus, TestDBusFlags}; + use tokio::sync::oneshot; + use zbus::zvariant::{LE, ObjectPath, OwnedValue, Value, serialized::Context, to_bytes}; + + use super::*; + + const REQUEST_HANDLE: &str = "/org/freedesktop/portal/desktop/request/1_42/t"; + + type TestResponse = HashMap<&'static str, Value<'static>>; + + fn encode( + value: &T, + ) -> zbus::zvariant::serialized::Data<'static, 'static> { + to_bytes(Context::new_dbus(LE, 0), value).unwrap() + } + + fn options(request_handle: Option<&str>) -> HashMap<&'static str, Value<'static>> { + let mut options = HashMap::from([ + ("top_origin", Value::from("https://example.com")), + ("public_key", Value::from("{}")), + ]); + if let Some(handle) = request_handle { + let path = ObjectPath::try_from(handle.to_string()).unwrap(); + options.insert("request_handle", Value::from(path)); + } + options + } + + fn decode_portal_result( + result: PortalResult>, Error>, + ) -> (u32, HashMap) { + encode(&result).deserialize().unwrap().0 + } + + #[test] + fn test_create_options_without_request_handle() { + let (options, _): (CreateCredentialPortalOptions, _) = + encode(&options(None)).deserialize().unwrap(); + assert_eq!(options.public_key.as_deref(), Some("{}")); + assert!(options.request_handle.is_none()); + } + + #[test] + fn test_create_options_with_request_handle() { + let (options, _): (CreateCredentialPortalOptions, _) = + encode(&options(Some(REQUEST_HANDLE))) + .deserialize() + .unwrap(); + assert_eq!(options.request_handle.unwrap().as_str(), REQUEST_HANDLE); + } + + #[test] + fn test_get_options_without_request_handle() { + let (options, _): (GetCredentialPortalOptions, _) = + encode(&options(None)).deserialize().unwrap(); + assert_eq!(options.top_origin.as_deref(), Some("https://example.com")); + assert!(options.request_handle.is_none()); + } + + #[test] + fn test_get_options_with_request_handle() { + let (options, _): (GetCredentialPortalOptions, _) = encode(&options(Some(REQUEST_HANDLE))) + .deserialize() + .unwrap(); + assert_eq!(options.request_handle.unwrap().as_str(), REQUEST_HANDLE); + } + + #[test] + fn test_portal_result_response_codes() { + let (code, results) = decode_portal_result(Ok(HashMap::new()).into()); + assert_eq!(code, PortalResponse::Success as u32); + assert!(results.is_empty()); + + let (code, results) = decode_portal_result(PortalResult::cancelled()); + assert_eq!(code, PortalResponse::Cancelled as u32); + assert!(results.is_empty()); + + let (code, results) = decode_portal_result(Err(Error::NotAllowedError).into()); + assert_eq!(code, PortalResponse::Other as u32); + assert!(results.contains_key("error")); + } + + #[tokio::test] + async fn test_ceremony_without_request_handle_is_not_cancellable() { + let result = run_ceremony( + &connect_test_bus(None).await.0, + None, + None, + |cancellation| async move { + assert!(!cancellation.is_cancelled()); + Ok(TestResponse::new()) + }, + ) + .await; + assert_eq!( + decode_portal_result(result).0, + PortalResponse::Success as u32 + ); + } + + #[tokio::test] + async fn test_invalid_request_handle_is_rejected() { + let (connection, _bus) = connect_test_bus(None).await; + let handle = OwnedObjectPath::try_from(PORTAL_SERVICE_PATH).unwrap(); + let result = run_ceremony( + &connection, + connection.unique_name().map(|n| n.inner()), + Some(handle), + |_| async { Ok(TestResponse::new()) }, + ) + .await; + assert!(matches!(result.inner, Some(Err(Error::TypeError)))); + } + + #[tokio::test] + async fn test_close_cancels_ceremony() { + let (gateway, bus) = connect_test_bus(None).await; + let (caller, _) = connect_test_bus(Some(&bus)).await; + let (other, _) = connect_test_bus(Some(&bus)).await; + let handle = OwnedObjectPath::try_from(REQUEST_HANDLE).unwrap(); + let (started_tx, started_rx) = oneshot::channel(); + + let ceremony = run_ceremony( + &gateway, + caller.unique_name().map(|n| n.inner()), + Some(handle.clone()), + |cancellation| async move { + started_tx.send(()).unwrap(); + // Like the credential service, fail once the request is cancelled. + cancellation.cancelled().await; + Err::(Error::NotAllowedError) + }, + ); + let client = async { + started_rx.await.unwrap(); + let err = close_request(&other, &gateway, &handle).await.unwrap_err(); + assert!(matches!(err, fdo::Error::AccessDenied(_)), "{err:?}"); + close_request(&caller, &gateway, &handle).await.unwrap(); + }; + let (result, ()) = tokio::join!(ceremony, client); + + let (code, _) = decode_portal_result(result); + assert_eq!(code, PortalResponse::Cancelled as u32); + // The request object is removed when the ceremony ends. + assert!(close_request(&caller, &gateway, &handle).await.is_err()); + } + + #[tokio::test] + async fn test_request_handle_removed_after_success() { + let (gateway, bus) = connect_test_bus(None).await; + let (caller, _) = connect_test_bus(Some(&bus)).await; + let handle = OwnedObjectPath::try_from(REQUEST_HANDLE).unwrap(); + + let result = run_ceremony( + &gateway, + caller.unique_name().map(|n| n.inner()), + Some(handle.clone()), + |_| async { Ok(TestResponse::new()) }, + ) + .await; + + assert_eq!( + decode_portal_result(result).0, + PortalResponse::Success as u32 + ); + assert!(close_request(&caller, &gateway, &handle).await.is_err()); + } + + /// Connects to a private test bus, starting one if `bus` is `None`. + async fn connect_test_bus(bus: Option<&TestBus>) -> (Connection, TestBus) { + let bus = match bus { + Some(bus) => bus.clone(), + None => TestBus::new(), + }; + let connection = zbus::connection::Builder::address(bus.address.as_str()) + .unwrap() + .build() + .await + .unwrap(); + (connection, bus) + } + + async fn close_request( + caller: &Connection, + gateway: &Connection, + handle: &OwnedObjectPath, + ) -> fdo::Result<()> { + caller + .call_method( + gateway.unique_name(), + handle, + Some("org.freedesktop.handler.portal.experimental.Request"), + "Close", + &(), + ) + .await + .map(|_| ()) + .map_err(fdo::Error::from) + } + + #[derive(Clone)] + struct TestBus { + address: String, + _bus: Rc, + } + + struct TestBusGuard(TestDBus); + + impl Drop for TestBusGuard { + fn drop(&mut self) { + self.0.down(); + } + } + + impl TestBus { + fn new() -> Self { + let bus = TestDBus::new(TestDBusFlags::NONE); + bus.up(); + let address = bus.bus_address().expect("test bus to be up").to_string(); + Self { + address, + _bus: Rc::new(TestBusGuard(bus)), + } + } + } #[test] fn test_ui_backend_defaults_when_missing_or_empty() { diff --git a/credentialsd/src/gateway/mod.rs b/credentialsd/src/gateway/mod.rs index 7c66e57..1207d4f 100644 --- a/credentialsd/src/gateway/mod.rs +++ b/credentialsd/src/gateway/mod.rs @@ -14,6 +14,7 @@ use std::{ use credentialsd_common::model::WindowHandle; use tokio::sync::Mutex as AsyncMutex; +use tokio_util::sync::CancellationToken; use zbus::{ Connection, names::OwnedWellKnownName, @@ -82,6 +83,7 @@ impl GatewayService { &self, request: CreateCredentialRequest, context: RequestContext, + cancellation: CancellationToken, parent_window: Option, activation_token: Option, ui_backend: Option, @@ -115,6 +117,7 @@ impl GatewayService { .request_credential( context.into(), cred_request, + cancellation, parent_window, activation_token, ui_backend, @@ -149,6 +152,7 @@ impl GatewayService { &self, request: GetCredentialRequest, context: RequestContext, + cancellation: CancellationToken, parent_window: Option, activation_token: Option, ui_backend: Option, @@ -179,6 +183,7 @@ impl GatewayService { .request_credential( context.into(), cred_request, + cancellation, parent_window, activation_token, ui_backend,