1
// org.freedesktop.Secret.Prompt
2

            
3
use std::{future::Future, os::fd::AsFd, pin::Pin, str::FromStr, sync::Arc};
4

            
5
use formatx::formatx;
6
use gettextrs::gettext;
7
use oo7::{Secret, dbus::ServiceError};
8
use tokio::{
9
    io::AsyncReadExt,
10
    sync::{Mutex, OnceCell},
11
};
12
use zbus::{
13
    interface,
14
    object_server::SignalEmitter,
15
    wire::{ObjectPath, Optional, OwnedObjectPath, OwnedVariant},
16
};
17

            
18
#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
19
use crate::gnome::prompter::{GNOMEPrompterCallback, GNOMEPrompterProxy};
20
#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
21
use crate::plasma::prompter::PlasmaPrompterCallback;
22
use crate::{
23
    error::custom_service_error,
24
    service::{PrompterType, Service},
25
};
26

            
27
#[zbus::proxy(
28
    interface = "org.freedesktop.secrets.CliPrompter",
29
    default_service = "org.freedesktop.secrets.CliPrompter",
30
    default_path = "/org/freedesktop/secrets/CliPrompter"
31
)]
32
trait CliPrompter {
33
    #[zbus(no_autostart)]
34
    async fn prompt(
35
        &self,
36
        label: &str,
37
        description: &str,
38
    ) -> zbus::Result<(zbus::wire::OwnedFd, bool)>;
39
}
40

            
41
pub const MAX_UNLOCK_ATTEMPTS: u32 = 5;
42

            
43
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44
pub enum PromptRole {
45
    Unlock,
46
    CreateCollection,
47
    ChangePassword,
48
}
49

            
50
/// A boxed future that represents the action to be taken when a prompt
51
/// completes
52
pub type PromptActionFuture =
53
    Pin<Box<dyn Future<Output = Result<OwnedVariant, ServiceError>> + Send + 'static>>;
54

            
55
/// Represents the action to be taken when a prompt completes
56
pub struct PromptAction {
57
    /// The async function to execute when the prompt is accepted
58
    action: Box<dyn FnOnce(Option<Secret>) -> PromptActionFuture + Send>,
59
}
60

            
61
impl PromptAction {
62
    /// Create a new prompt action from a closure that takes an optional secret
63
    /// and returns a future
64
38
    pub fn new<F, Fut>(f: F) -> Self
65
    where
66
        F: FnOnce(Option<Secret>) -> Fut + Send + 'static,
67
        Fut: Future<Output = Result<OwnedVariant, ServiceError>> + Send + 'static,
68
    {
69
        Self {
70
116
            action: Box::new(move |secret| Box::pin(f(secret))),
71
        }
72
    }
73

            
74
    /// Execute the action with the provided secret
75
46
    pub async fn execute(self, secret: Option<Secret>) -> Result<OwnedVariant, ServiceError> {
76
31
        (self.action)(secret).await
77
    }
78
}
79

            
80
#[derive(Clone)]
81
pub struct Prompt {
82
    service: Service,
83
    role: PromptRole,
84
    path: OwnedObjectPath,
85
    /// The label of the collection/keyring being prompted for
86
    label: String,
87
    /// The collection for Unlock prompts (needed for secret validation)
88
    collection: Option<crate::collection::Collection>,
89
    /// GNOME Specific
90
    #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
91
    gnome_callback: Arc<OnceCell<GNOMEPrompterCallback>>,
92
    /// KDE Plasma Specific
93
    #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
94
    plasma_callback: Arc<OnceCell<PlasmaPrompterCallback>>,
95
    /// The action to execute when the prompt completes
96
    action: Arc<Mutex<Option<PromptAction>>>,
97
}
98

            
99
#[cfg(any(
100
    feature = "gnome_openssl_crypto",
101
    feature = "gnome_native_crypto",
102
    feature = "plasma_native_crypto",
103
    feature = "plasma_openssl_crypto"
104
))] // User has to enable at least one prompt backend
105
#[interface(name = "org.freedesktop.Secret.Prompt")]
106
impl Prompt {
107
7
    pub async fn prompt(
108
        &self,
109
        window_id: Optional<&str>,
110
        #[zbus(header)] header: zbus::message::Header<'_>,
111
    ) -> Result<(), ServiceError> {
112
12
        let window_id = (*window_id).and_then(|w| ashpd::WindowIdentifierType::from_str(w).ok());
113
12
        let peer_info = match Service::sender(&header) {
114
6
            Some(sender) => self.service.peer_info(&sender).await,
115
            None => None,
116
        };
117

            
118
12
        match self.service.prompter_type(peer_info.as_ref()).await {
119
            #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
120
8
            PrompterType::Plasma => self.prompt_plasma(window_id).await,
121
            #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
122
8
            PrompterType::GNOME => self.prompt_gnome(window_id).await,
123
12
            PrompterType::Cli => self.prompt_cli().await,
124
            #[allow(unreachable_patterns)]
125
            _ => Err(custom_service_error(
126
                "No prompt backend available in the current environment.",
127
            )),
128
        }
129
    }
130

            
131
19
    pub async fn dismiss(&self) -> Result<(), ServiceError> {
132
        #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
133
10
        if let Some(callback) = self.plasma_callback.get() {
134
            let emitter = SignalEmitter::from_parts(
135
                self.service.connection().clone(),
136
                callback.path().clone(),
137
            );
138
            PlasmaPrompterCallback::dismiss(&emitter).await?;
139
        }
140

            
141
        #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
142
10
        if let Some(_callback) = self.gnome_callback.get() {
143
            // TODO: figure out if we should destroy the un-export the callback
144
            // here?
145
        }
146

            
147
25
        self.service
148
            .object_server()
149
5
            .remove::<Self, _>(&self.path)
150
15
            .await?;
151
5
        self.service.remove_prompt(&self.path).await;
152

            
153
4
        Ok(())
154
    }
155

            
156
    #[zbus(signal, name = "Completed")]
157
    pub async fn completed(
158
5
        signal_emitter: &SignalEmitter<'_>,
159
5
        dismissed: bool,
160
10
        result: OwnedVariant,
161
    ) -> zbus::Result<()>;
162
}
163

            
164
impl Prompt {
165
12
    pub async fn new(
166
        service: Service,
167
        role: PromptRole,
168
        label: String,
169
        collection: Option<crate::collection::Collection>,
170
    ) -> Self {
171
25
        let index = service.prompt_index();
172
13
        let path =
173
            OwnedObjectPath::try_from(format!("/org/freedesktop/secrets/prompt/p{index}")).unwrap();
174
12
        Self::with_path(service, role, label, collection, path)
175
    }
176

            
177
15
    pub fn with_path(
178
        service: Service,
179
        role: PromptRole,
180
        label: String,
181
        collection: Option<crate::collection::Collection>,
182
        path: OwnedObjectPath,
183
    ) -> Self {
184
        Self {
185
            path,
186
            service,
187
            role,
188
            label,
189
            collection,
190
            #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
191
29
            gnome_callback: Default::default(),
192
            #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
193
29
            plasma_callback: Default::default(),
194
29
            action: Arc::new(Mutex::new(None)),
195
        }
196
    }
197

            
198
14
    pub fn path(&self) -> &ObjectPath<'_> {
199
15
        &self.path
200
    }
201

            
202
11
    pub fn role(&self) -> PromptRole {
203
11
        self.role
204
    }
205

            
206
12
    pub fn label(&self) -> &str {
207
12
        &self.label
208
    }
209

            
210
8
    pub(crate) fn collection(&self) -> Option<&crate::collection::Collection> {
211
8
        self.collection.as_ref()
212
    }
213

            
214
    /// Set the action to execute when the prompt completes
215
61
    pub async fn set_action(&self, action: PromptAction) {
216
15
        *self.action.lock().await = Some(action);
217
    }
218

            
219
    /// Take the action, consuming it so it can only be executed once
220
46
    async fn take_action(&self) -> Option<PromptAction> {
221
23
        self.action.lock().await.take()
222
    }
223

            
224
40
    pub async fn on_unlock_collection(&self, secret: Option<Secret>) -> Result<bool, ServiceError> {
225
        debug_assert_eq!(self.role, PromptRole::Unlock);
226

            
227
        // Get the collection to validate the secret
228
8
        let collection = self.collection().expect("Unlock requires a collection");
229
8
        let label = self.label();
230

            
231
        // The placeholder of a pending migration accepts any secret;
232
        // validate against the legacy keyring instead.
233
        let pending_migration = {
234
8
            let pending = self.service.pending_migrations.lock().await;
235
16
            pending.get(collection.name()).cloned()
236
        };
237

            
238
8
        let is_valid = if let Some(migration) = pending_migration {
239
8
            match secret.as_ref() {
240
12
                Some(secret) => migration.validate_secret(secret).await.map_err(|err| {
241
                    custom_service_error(&format!(
242
                        "Failed to validate secret for {label} keyring: {err}."
243
                    ))
244
                })?,
245
                // A pending migration always requires a secret.
246
                None => false,
247
            }
248
28
        } else if let Some(ref secret) = secret {
249
            // Validate the secret using the already-open keyring
250
16
            let keyring_guard = collection.keyring.read().await;
251
40
            let valid = keyring_guard
252
                .as_ref()
253
                .unwrap()
254
8
                .validate_secret(secret)
255
24
                .await
256
16
                .map_err(|err| {
257
                    custom_service_error(&format!(
258
                        "Failed to validate secret for {label} keyring: {err}."
259
                    ))
260
                })?;
261
8
            drop(keyring_guard);
262
8
            valid
263
        } else {
264
            // No secret means unencrypted -> validate items are plaintext
265
            let keyring_guard = collection.keyring.read().await;
266
            let valid = keyring_guard
267
                .as_ref()
268
                .unwrap()
269
                .validate_unencrypted()
270
                .await
271
                .map_err(|err| {
272
                    custom_service_error(&format!(
273
                        "Failed to validate unencrypted keyring {label}: {err}."
274
                    ))
275
                })?;
276
            drop(keyring_guard);
277
            valid
278
        };
279

            
280
20
        if is_valid {
281
18
            tracing::debug!("Keyring secret matches for {label}.");
282

            
283
16
            let Some(action) = self.take_action().await else {
284
                return Err(custom_service_error(
285
                    "Prompt action was already executed or not set",
286
                ));
287
            };
288

            
289
            // Execute the unlock action after successful validation
290
20
            let result_value = match action.execute(secret).await {
291
8
                Ok(value) => value,
292
                Err(err) => {
293
                    self.emit_dismissed().await;
294
                    return Err(err);
295
                }
296
            };
297

            
298
16
            let prompt_path = self.path().to_owned();
299
16
            let signal_emitter = self.service.signal_emitter(&prompt_path)?;
300
32
            tokio::spawn(async move {
301
20
                tracing::debug!("Unlock prompt completed.");
302
16
                let _ = Prompt::completed(&signal_emitter, false, result_value).await;
303
            });
304
8
            Ok(true)
305
        } else {
306
9
            tracing::error!("Keyring {label} failed to unlock, incorrect secret.");
307

            
308
4
            Ok(false)
309
        }
310
    }
311

            
312
54
    pub async fn on_create_collection(&self, secret: Option<Secret>) -> Result<(), ServiceError> {
313
        debug_assert_eq!(self.role, PromptRole::CreateCollection);
314

            
315
11
        let Some(action) = self.take_action().await else {
316
            return Err(custom_service_error(
317
                "Prompt action was already executed or not set",
318
            ));
319
        };
320

            
321
        // Execute the collection creation action with the secret
322
32
        match action.execute(secret).await {
323
11
            Ok(collection_path_value) => {
324
28
                tracing::info!("CreateCollection action completed successfully");
325

            
326
24
                let signal_emitter = self.service.signal_emitter(self.path().to_owned())?;
327

            
328
48
                tokio::spawn(async move {
329
30
                    tracing::debug!("CreateCollection prompt completed.");
330
23
                    let _ = Prompt::completed(&signal_emitter, false, collection_path_value).await;
331
                });
332
13
                Ok(())
333
            }
334
            Err(err) => {
335
                self.emit_dismissed().await;
336
                Err(err)
337
            }
338
        }
339
    }
340

            
341
20
    pub async fn on_change_password(&self, secret: Option<Secret>) -> Result<(), ServiceError> {
342
        debug_assert_eq!(self.role, PromptRole::ChangePassword);
343

            
344
4
        let Some(action) = self.take_action().await else {
345
            return Err(custom_service_error(
346
                "Prompt action was already executed or not set",
347
            ));
348
        };
349

            
350
        // Execute the change password action with the new secret
351
13
        match action.execute(secret).await {
352
4
            Ok(result) => {
353
8
                tracing::info!("ChangePassword action completed successfully");
354

            
355
8
                let signal_emitter = self.service.signal_emitter(self.path().to_owned())?;
356

            
357
16
                tokio::spawn(async move {
358
8
                    tracing::debug!("ChangePassword prompt completed.");
359
8
                    let _ = Prompt::completed(&signal_emitter, false, result).await;
360
                });
361
4
                Ok(())
362
            }
363
4
            Err(err) => {
364
8
                self.emit_dismissed().await;
365
4
                Err(err)
366
            }
367
        }
368
    }
369

            
370
16
    pub(crate) async fn emit_orphaned_completed(&self) -> Result<(), ServiceError> {
371
8
        let signal_emitter = self.service.signal_emitter(self.path().to_owned())?;
372
8
        let result = zbus::wire::Variant::new::<Vec<OwnedObjectPath>>(vec![])
373
            .try_into_owned()
374
            .unwrap();
375
4
        Prompt::completed(&signal_emitter, true, result).await?;
376
4
        Ok(())
377
    }
378

            
379
16
    async fn emit_dismissed(&self) {
380
12
        if let Ok(signal_emitter) = self.service.signal_emitter(self.path().to_owned()) {
381
8
            let result = zbus::wire::Variant::new::<Vec<OwnedObjectPath>>(vec![])
382
                .try_into_owned()
383
                .unwrap();
384
4
            let _ = Prompt::completed(&signal_emitter, true, result).await;
385
        }
386
    }
387

            
388
    #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
389
4
    async fn prompt_plasma(
390
        &self,
391
        window_id: Option<ashpd::WindowIdentifierType>,
392
    ) -> Result<(), ServiceError> {
393
8
        if self.plasma_callback.get().is_some() {
394
4
            return Ok(());
395
        }
396

            
397
4
        let callback = PlasmaPrompterCallback::new(self.service.clone(), self.path.clone()).await;
398
8
        let path = OwnedObjectPath::from(callback.path().clone());
399

            
400
8
        let _ = self.plasma_callback.set(callback.clone());
401
20
        self.service
402
            .object_server()
403
8
            .at(&path, callback.clone())
404
16
            .await?;
405
4
        tracing::debug!("Prompt `{}` created.", self.path);
406

            
407
4
        callback.start(&self.role, window_id, &self.label).await
408
    }
409

            
410
    #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
411
14
    async fn prompt_gnome(
412
        &self,
413
        window_id: Option<ashpd::WindowIdentifierType>,
414
    ) -> Result<(), ServiceError> {
415
28
        if self.gnome_callback.get().is_some() {
416
4
            return Ok(());
417
        };
418

            
419
63
        let callback =
420
            GNOMEPrompterCallback::new(window_id, self.service.clone(), self.path.clone())
421
41
                .await
422
14
                .map_err(|err| {
423
                    custom_service_error(&format!("Failed to create GNOMEPrompterCallback {err}."))
424
                })?;
425

            
426
27
        let path = OwnedObjectPath::from(callback.path().clone());
427

            
428
27
        let _ = self.gnome_callback.set(callback.clone());
429
15
        self.service.object_server().at(&path, callback).await?;
430
20
        tracing::debug!("Prompt `{}` created.", self.path);
431

            
432
25
        let prompter = GNOMEPrompterProxy::new(&self.service.connection()).await?;
433
39
        tokio::spawn(async move { prompter.begin_prompting(&path).await });
434

            
435
13
        Ok(())
436
    }
437

            
438
24
    async fn prompt_cli(&self) -> Result<(), ServiceError> {
439
24
        let proxy = CliPrompterProxy::new(&self.service.connection())
440
12
            .await
441
8
            .map_err(|e| custom_service_error(&format!("CLI prompter not available: {e}")))?;
442

            
443
4
        let label = &self.label;
444
4
        let description = match self.role {
445
8
            PromptRole::Unlock => formatx!(
446
4
                gettext("An application wants access to the keyring “{}”, but it is locked"),
447
                label,
448
            )
449
            .expect("Wrong format in translatable string"),
450
            PromptRole::CreateCollection => formatx!(
451
                gettext("An application wants to create a new keyring called “{}”. Choose the password you want to use for it."),
452
                label,
453
            )
454
            .expect("Wrong format in translatable string"),
455
            PromptRole::ChangePassword => formatx!(
456
                gettext("An application wants to change the password for the “{}” keyring. Choose the new password you want to use for it."),
457
                label,
458
            )
459
            .expect("Wrong format in translatable string"),
460
        };
461

            
462
4
        let mut attempts = 0;
463
4
        loop {
464
20
            let (fd, accepted) = match proxy.prompt(&self.label, &description).await {
465
4
                Ok(result) => result,
466
                Err(e) => return Err(custom_service_error(&format!("CLI prompter failed: {e}"))),
467
            };
468
4
            if !accepted {
469
8
                tracing::info!("CLI prompter dismissed by user.");
470
8
                return Err(custom_service_error("Prompt dismissed by user."));
471
            }
472

            
473
            let std_stream = std::os::unix::net::UnixStream::from(
474
8
                fd.as_fd().try_clone_to_owned().expect("Failed to clone fd"),
475
            );
476
8
            std_stream
477
                .set_nonblocking(true)
478
4
                .map_err(|e| custom_service_error(&format!("Failed to set non-blocking: {e}")))?;
479
4
            let mut stream = tokio::net::UnixStream::from_std(std_stream)
480
                .expect("Failed to create Tokio UnixStream");
481
4
            let mut buffer = zeroize::Zeroizing::new(Vec::new());
482
12
            stream.read_to_end(&mut buffer).await.map_err(|e| {
483
                custom_service_error(&format!("Failed to read secret from CLI prompter: {e}"))
484
            })?;
485
4
            let secret = if buffer.is_empty() {
486
                None
487
            } else {
488
8
                Some(Secret::from(buffer.as_slice()))
489
            };
490

            
491
4
            match self.role {
492
                PromptRole::Unlock => {
493
16
                    if self.on_unlock_collection(secret).await? {
494
4
                        return Ok(());
495
                    }
496

            
497
8
                    attempts += 1;
498
4
                    if attempts >= MAX_UNLOCK_ATTEMPTS {
499
8
                        tracing::warn!(
500
                            "Maximum unlock attempts ({MAX_UNLOCK_ATTEMPTS}) reached, \
501
                             dismissing prompt."
502
                        );
503
8
                        self.emit_dismissed().await;
504
4
                        return Ok(());
505
                    }
506
                    // Prompt again, the secret was incorrect
507
                }
508
                PromptRole::CreateCollection => {
509
                    self.on_create_collection(secret).await?;
510
                    return Ok(());
511
                }
512
                PromptRole::ChangePassword => {
513
                    self.on_change_password(secret).await?;
514
                    return Ok(());
515
                }
516
            }
517
        }
518
    }
519
}
520

            
521
#[cfg(test)]
522
mod tests;