1
// org.freedesktop.Secret.Service
2

            
3
mod discovery;
4
mod lifecycle;
5
mod locking;
6
mod naming;
7

            
8
use std::{
9
    collections::HashMap,
10
    sync::{
11
        Arc, RwLock,
12
        atomic::{AtomicU32, Ordering},
13
    },
14
};
15

            
16
use oo7::{
17
    Key, Secret,
18
    dbus::{
19
        Algorithm, ServiceError,
20
        api::{DBusSecretInner, Properties},
21
    },
22
    file::{Keyring, UnlockedKeyring},
23
};
24
use tokio::sync::Mutex;
25
use zbus::{
26
    names::UniqueName,
27
    object_server::SignalEmitter,
28
    proxy::Defaults,
29
    wire::{ObjectPath, OwnedObjectPath, OwnedVariant, Variant},
30
};
31

            
32
#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
33
use crate::plasma::prompter::in_plasma_environment;
34
use crate::{
35
    collection::Collection,
36
    error::custom_service_error,
37
    migration::PendingMigration,
38
    prompt::{Prompt, PromptAction, PromptRole},
39
    session::{PeerInfo, Session},
40
};
41

            
42
#[cfg(any(test, feature = "test-util"))]
43
pub(crate) const P2P_TEST_SENDER: &str = ":p2p.test";
44

            
45
/// Prompter type
46
#[derive(Clone, Copy, PartialEq, Eq)]
47
pub enum PrompterType {
48
    #[allow(clippy::upper_case_acronyms)]
49
    GNOME,
50
    Plasma,
51
    Cli,
52
}
53

            
54
#[derive(Clone)]
55
pub struct Service {
56
    // Properties
57
    pub(crate) collections: Arc<Mutex<HashMap<OwnedObjectPath, Collection>>>,
58
    // Other attributes
59
    connection: Arc<RwLock<Option<zbus::Connection>>>,
60
    // sessions mapped to their corresponding object path on the bus
61
    sessions: Arc<Mutex<HashMap<OwnedObjectPath, Session>>>,
62
    session_index: Arc<AtomicU32>,
63
    // prompts mapped to their corresponding object path on the bus
64
    prompts: Arc<Mutex<HashMap<OwnedObjectPath, Prompt>>>,
65
    prompt_index: Arc<AtomicU32>,
66
    // pending collection creations: prompt_path -> (label, alias)
67
    pending_collections: Arc<Mutex<HashMap<OwnedObjectPath, (String, String)>>>,
68
    // pending unlock: object_path -> prompt path (for deduplication)
69
    pending_unlocks: Arc<Mutex<HashMap<OwnedObjectPath, OwnedObjectPath>>>,
70
    // pending keyring migrations: name -> migration
71
    pub(crate) pending_migrations: Arc<Mutex<HashMap<String, PendingMigration>>>,
72
    // Data directory for keyrings (e.g., ~/.local/share or test temp dir)
73
    data_dir: std::path::PathBuf,
74
    // PAM socket path (None for tests that don't need PAM listener)
75
    pub(crate) pam_socket: Option<std::path::PathBuf>,
76
    // Override for prompter type (mainly for tests)
77
    pub(crate) prompter_type_override: Arc<Mutex<Option<PrompterType>>>,
78
    // Whether encrypted sessions are supported
79
    encrypted_supported: bool,
80
}
81

            
82
#[zbus::interface(name = "org.freedesktop.Secret.Service")]
83
impl Service {
84
    #[zbus(out_args("output", "result"))]
85
33
    pub async fn open_session(
86
        &self,
87
        algorithm: Algorithm,
88
        input: Variant<'_>,
89
        #[zbus(header)] header: zbus::message::Header<'_>,
90
        #[zbus(object_server)] object_server: &zbus::ObjectServer,
91
    ) -> Result<(OwnedVariant, OwnedObjectPath), ServiceError> {
92
59
        let (public_key, aes_key) = match algorithm {
93
32
            Algorithm::Plain => (None, None),
94
16
            Algorithm::Encrypted if !self.encrypted_supported => {
95
2
                return Err(ServiceError::ZBus(zbus::Error::FDO(Box::new(
96
2
                    zbus::fdo::Error::NotSupported(
97
                        "Algorithm dh-ietf1024-sha256-aes128-cbc-pkcs7 is not supported"
98
2
                            .to_string(),
99
                    ),
100
                ))));
101
            }
102
            Algorithm::Encrypted => {
103
31
                let client_public_key = Key::try_from(input).map_err(|err| {
104
                    custom_service_error(&format!(
105
                        "Input Variant could not be converted into a Key {err}."
106
                    ))
107
                })?;
108
32
                let private_key = Key::generate_private_key().map_err(|err| {
109
                    custom_service_error(&format!("Failed to generate private key {err}."))
110
                })?;
111
                (
112
32
                    Some(Key::generate_public_key(&private_key).map_err(|err| {
113
                        custom_service_error(&format!("Failed to generate public key {err}."))
114
                    })?),
115
15
                    Some(
116
32
                        Key::generate_aes_key(&private_key, &client_public_key).map_err(|err| {
117
                            custom_service_error(&format!("Failed to generate aes key {err}."))
118
                        })?,
119
                    ),
120
                )
121
            }
122
        };
123

            
124
68
        let sender = Self::sender(&header)
125
30
            .ok_or_else(|| custom_service_error("Failed to get sender from header."))?;
126
64
        let peer_info = PeerInfo::lookup(&self.connection(), &sender).await;
127
        let session = Session::new(
128
67
            aes_key.map(Arc::new),
129
63
            self.clone(),
130
32
            sender.clone(),
131
31
            peer_info,
132
        )
133
94
        .await;
134
60
        let path = OwnedObjectPath::from(session.path().clone());
135

            
136
60
        match session.peer_info() {
137
30
            Some(info) => {
138
60
                tracing::info!("Client {} ({}) connected, session: {}", sender, info, path)
139
            }
140
            None => tracing::info!("Client {} connected, session: {}", sender, path),
141
        }
142

            
143
149
        self.sessions
144
            .lock()
145
88
            .await
146
61
            .insert(path.clone(), session.clone());
147

            
148
32
        object_server.at(&path, session).await?;
149

            
150
31
        let service_key = public_key
151
32
            .map(OwnedVariant::from)
152
102
            .unwrap_or_else(|| Variant::new::<Vec<u8>>(vec![]).try_into_owned().unwrap());
153

            
154
31
        Ok((service_key, path))
155
    }
156

            
157
    #[zbus(out_args("collection", "prompt"))]
158
11
    pub async fn create_collection(
159
        &self,
160
        properties: Properties,
161
        alias: &str,
162
    ) -> Result<(OwnedObjectPath, ObjectPath<'_>), ServiceError> {
163
21
        let label = properties.label().to_owned();
164
21
        let alias = alias.to_owned();
165

            
166
        // Create a prompt to get the password for the new collection
167
        let prompt = Prompt::new(
168
21
            self.clone(),
169
            PromptRole::CreateCollection,
170
10
            label.clone(),
171
11
            None,
172
        )
173
31
        .await;
174
21
        let prompt_path = OwnedObjectPath::from(prompt.path().clone());
175

            
176
        // Store the collection metadata for later creation
177
44
        self.pending_collections
178
            .lock()
179
30
            .await
180
10
            .insert(prompt_path.clone(), (label, alias));
181

            
182
        // Create the collection creation action
183
21
        let service = self.clone();
184
11
        let creation_prompt_path = prompt_path.clone();
185
52
        let action = PromptAction::new(move |secret: Option<Secret>| async move {
186
47
            let collection_path = service
187
21
                .complete_collection_creation(&creation_prompt_path, secret)
188
43
                .await?;
189

            
190
24
            Ok(Variant::new(collection_path).try_into_owned().unwrap())
191
        });
192

            
193
11
        prompt.set_action(action).await;
194

            
195
        // Register the prompt
196
55
        self.prompts
197
            .lock()
198
30
            .await
199
20
            .insert(prompt_path.clone(), prompt.clone());
200

            
201
11
        self.object_server().at(&prompt_path, prompt).await?;
202

            
203
10
        tracing::debug!("CreateCollection prompt created at `{}`", prompt_path);
204

            
205
        // Return empty collection path and the prompt path
206
21
        Ok((OwnedObjectPath::default(), prompt_path.into()))
207
    }
208

            
209
    #[zbus(out_args("unlocked", "locked"))]
210
4
    pub async fn search_items(
211
        &self,
212
        attributes: HashMap<String, String>,
213
    ) -> Result<(Vec<OwnedObjectPath>, Vec<OwnedObjectPath>), ServiceError> {
214
4
        let mut unlocked = Vec::new();
215
4
        let mut locked = Vec::new();
216
8
        let snapshot = self.sorted_collections().await;
217

            
218
12
        for collection in &snapshot {
219
16
            let items = collection.search_inner_items(&attributes).await?;
220
8
            for item in items {
221
16
                if item.is_locked().await {
222
8
                    locked.push(item.path().clone().into());
223
                } else {
224
8
                    unlocked.push(item.path().clone().into());
225
                }
226
            }
227
        }
228

            
229
8
        if unlocked.is_empty() && locked.is_empty() {
230
8
            tracing::debug!(
231
                "Items with attributes {:?} does not exist in any collection.",
232
                attributes
233
            );
234
        } else {
235
8
            tracing::debug!("Items with attributes {:?} found.", attributes);
236
        }
237

            
238
4
        Ok((unlocked, locked))
239
    }
240

            
241
    #[zbus(out_args("unlocked", "prompt"))]
242
10
    pub async fn unlock(
243
        &self,
244
        objects: Vec<OwnedObjectPath>,
245
    ) -> Result<(Vec<OwnedObjectPath>, OwnedObjectPath), ServiceError> {
246
20
        tracing::info!("Unlock requested for {} objects.", objects.len());
247
20
        let (unlocked, not_unlocked) = self.set_locked(false, &objects).await?;
248
20
        if !not_unlocked.is_empty() {
249
            // Hold the lock across both the lookup and the registration so
250
            // a concurrent Unlock cannot slip between the two.
251
16
            let mut pending = self.pending_unlocks.lock().await;
252

            
253
            // Another unlock for the same object(s) is already prompting;
254
            // return the same prompt path so both callers share one prompt.
255
24
            if let Some(prompt_path) = not_unlocked
256
                .iter()
257
24
                .find_map(|obj| pending.get(obj).cloned())
258
            {
259
5
                drop(pending);
260
5
                return Ok((unlocked, prompt_path));
261
            }
262

            
263
            // First caller: reserve the prompt path while holding the lock
264
            // so concurrent callers see it before the Prompt is fully created.
265
16
            let index = self.prompt_index();
266
16
            let prompt_path =
267
                OwnedObjectPath::try_from(format!("/org/freedesktop/secrets/prompt/p{index}"))
268
                    .unwrap();
269
16
            for obj in &not_unlocked {
270
16
                pending.insert(obj.clone(), prompt_path.clone());
271
            }
272
8
            drop(pending);
273

            
274
16
            let collection = self.collection_for_objects(&not_unlocked).await;
275
8
            let label = if let Some(c) = &collection {
276
16
                c.label().await
277
            } else {
278
                String::default()
279
            };
280

            
281
            let prompt = Prompt::with_path(
282
8
                self.clone(),
283
                PromptRole::Unlock,
284
8
                label,
285
8
                collection,
286
8
                prompt_path,
287
            );
288
16
            let path = OwnedObjectPath::from(prompt.path().clone());
289

            
290
16
            let service = self.clone();
291
8
            let not_unlocked_for_action = not_unlocked.clone();
292
40
            let action = PromptAction::new(move |secret: Option<Secret>| async move {
293
16
                service
294
16
                    .perform_unlock(&not_unlocked_for_action, secret)
295
20
                    .await;
296
16
                Ok(Variant::new(not_unlocked_for_action)
297
8
                    .try_into_owned()
298
8
                    .unwrap())
299
            });
300

            
301
8
            prompt.set_action(action).await;
302

            
303
40
            self.prompts
304
                .lock()
305
24
                .await
306
16
                .insert(path.clone(), prompt.clone());
307

            
308
8
            self.object_server().at(&path, prompt).await?;
309
8
            return Ok((unlocked, path));
310
        }
311

            
312
8
        Ok((unlocked, OwnedObjectPath::default()))
313
    }
314

            
315
    #[zbus(out_args("locked", "Prompt"))]
316
10
    pub async fn lock(
317
        &self,
318
        objects: Vec<OwnedObjectPath>,
319
    ) -> Result<(Vec<OwnedObjectPath>, OwnedObjectPath), ServiceError> {
320
20
        tracing::info!("Lock requested for {} objects.", objects.len());
321
21
        let (locked, not_locked) = self.set_locked(true, &objects).await?;
322
        // Locking never requires prompts, so not_locked should always be empty
323
        debug_assert!(
324
            not_locked.is_empty(),
325
            "Lock operation should never require prompts"
326
        );
327
10
        Ok((locked, OwnedObjectPath::default()))
328
    }
329

            
330
    #[zbus(out_args("secrets"))]
331
4
    pub async fn get_secrets(
332
        &self,
333
        items: Vec<OwnedObjectPath>,
334
        session: OwnedObjectPath,
335
    ) -> Result<HashMap<OwnedObjectPath, DBusSecretInner>, ServiceError> {
336
6
        tracing::debug!(
337
            "GetSecrets called for {} items with session {}.",
338
            items.len(),
339
            session
340
        );
341
4
        let mut secrets = HashMap::new();
342
8
        let snapshot = self.sorted_collections().await;
343

            
344
20
        'outer: for collection in &snapshot {
345
20
            for item in &items {
346
14
                if let Some(item) = collection.item_from_path(item).await {
347
15
                    match item.get_secret(session.clone()).await {
348
4
                        Ok((secret,)) => {
349
8
                            secrets.insert(item.path().clone().into(), secret);
350
                            // To avoid iterating through all the remaining
351
                            // collections, if the items secrets are already
352
                            // retrieved.
353
4
                            if secrets.len() == items.len() {
354
                                break 'outer;
355
                            }
356
                        }
357
                        // Avoid erroring out if an item is locked.
358
                        Err(ServiceError::IsLocked(_)) => {
359
                            continue;
360
                        }
361
4
                        Err(err) => {
362
4
                            return Err(err);
363
                        }
364
                    };
365
                }
366
            }
367
        }
368

            
369
2
        tracing::debug!(
370
            "GetSecrets returned {} of {} requested secrets.",
371
            secrets.len(),
372
            items.len()
373
        );
374
4
        Ok(secrets)
375
    }
376

            
377
    #[zbus(out_args("collection"))]
378
110
    pub async fn read_alias(&self, name: &str) -> Result<OwnedObjectPath, ServiceError> {
379
44
        let collections = self.sorted_collections().await;
380
74
        if let Some(path) = Self::find_by_alias(&collections, name).await {
381
45
            tracing::debug!("Collection: {} found for alias: {}.", path, name);
382
20
            Ok(path)
383
        } else {
384
12
            tracing::info!("Collection with alias {} does not exist.", name);
385
12
            Ok(OwnedObjectPath::default())
386
        }
387
    }
388

            
389
4
    pub async fn set_alias(
390
        &self,
391
        name: &str,
392
        collection: OwnedObjectPath,
393
    ) -> Result<(), ServiceError> {
394
        // An alias points at a single collection, clear it from any other
395
        // holder so resolving it stays deterministic
396
16
        for other in self.sorted_collections().await {
397
12
            if other.path().as_str() != collection.as_str() && other.alias().await == name {
398
8
                other.set_alias("").await;
399
            }
400
        }
401

            
402
4
        let collections = self.collections.lock().await;
403

            
404
12
        for (path, other_collection) in collections.iter() {
405
8
            if *path == collection {
406
4
                other_collection.set_alias(name).await;
407

            
408
4
                tracing::info!("Collection: {} alias updated to {}.", collection, name);
409
4
                return Ok(());
410
            }
411
        }
412

            
413
4
        tracing::info!("Collection: {} does not exist.", collection);
414

            
415
8
        Err(ServiceError::NoSuchObject(format!(
416
            "The collection: {collection} does not exist.",
417
        )))
418
    }
419

            
420
    #[zbus(property, name = "Collections")]
421
122
    pub async fn collections(&self) -> Vec<OwnedObjectPath> {
422
69
        self.collections.lock().await.keys().cloned().collect()
423
    }
424

            
425
    #[zbus(signal, name = "CollectionCreated")]
426
    pub async fn collection_created(
427
12
        signal_emitter: &SignalEmitter<'_>,
428
10
        collection: &ObjectPath<'_>,
429
    ) -> zbus::Result<()>;
430

            
431
    #[zbus(signal, name = "CollectionDeleted")]
432
    pub async fn collection_deleted(
433
10
        signal_emitter: &SignalEmitter<'_>,
434
10
        collection: &ObjectPath<'_>,
435
    ) -> zbus::Result<()>;
436

            
437
    #[zbus(signal, name = "CollectionChanged")]
438
    pub async fn collection_changed(
439
13
        signal_emitter: &SignalEmitter<'_>,
440
13
        collection: &ObjectPath<'_>,
441
    ) -> zbus::Result<()>;
442
}
443

            
444
impl Service {
445
    const LOGIN_ALIAS: &str = "login";
446

            
447
    /// Set the prompter type override
448
    #[allow(unused)]
449
96
    pub(crate) async fn set_prompter_type(&self, prompter_type: PrompterType) {
450
52
        *self.prompter_type_override.lock().await = Some(prompter_type);
451
    }
452

            
453
    /// Get the prompter type to use based on the caller's session type
454
61
    pub(crate) async fn prompter_type(&self, peer_info: Option<&PeerInfo>) -> PrompterType {
455
16
        let is_graphical = peer_info
456
48
            .map(|p| p.session_type().is_graphical())
457
            .unwrap_or_default();
458

            
459
16
        if is_graphical {
460
46
            if let Some(override_type) = self.prompter_type_override.lock().await.as_ref() {
461
16
                return *override_type;
462
            }
463

            
464
            #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
465
            {
466
                if in_plasma_environment(&self.connection()).await {
467
                    return PrompterType::Plasma;
468
                }
469
            }
470

            
471
            return PrompterType::GNOME;
472
        }
473

            
474
        PrompterType::Cli
475
    }
476

            
477
37
    pub(crate) fn new(
478
        data_dir: std::path::PathBuf,
479
        pam_socket: Option<std::path::PathBuf>,
480
        encrypted_supported: bool,
481
    ) -> Self {
482
        Self {
483
75
            collections: Arc::new(Mutex::new(HashMap::new())),
484
76
            connection: Default::default(),
485
76
            sessions: Arc::new(Mutex::new(HashMap::new())),
486
76
            session_index: Arc::new(AtomicU32::new(0)),
487
76
            prompts: Arc::new(Mutex::new(HashMap::new())),
488
76
            prompt_index: Arc::new(AtomicU32::new(0)),
489
76
            pending_collections: Arc::new(Mutex::new(HashMap::new())),
490
76
            pending_unlocks: Arc::new(Mutex::new(HashMap::new())),
491
76
            pending_migrations: Arc::new(Mutex::new(HashMap::new())),
492
            data_dir,
493
            pam_socket,
494
76
            prompter_type_override: Arc::new(Mutex::new(None)),
495
            encrypted_supported,
496
        }
497
    }
498

            
499
23
    pub fn connection(&self) -> zbus::Connection {
500
51
        self.connection
501
            .read()
502
            .unwrap()
503
            .clone()
504
            .expect("service is not initialized")
505
    }
506

            
507
23
    pub fn object_server(&self) -> zbus::ObjectServer {
508
28
        self.connection().object_server().clone()
509
    }
510

            
511
    /// Drop the service's reference to its connection.
512
    ///
513
    /// The connection's object server holds the service, which in turn holds
514
    /// the connection, so neither is ever freed otherwise.
515
    #[cfg(any(test, feature = "test-util"))]
516
    #[allow(dead_code)]
517
16
    pub(crate) fn release_connection(&self) {
518
16
        self.connection.write().unwrap().take();
519
    }
520

            
521
10
    async fn resolve_alias(
522
        collections: &[Collection],
523
        path: &ObjectPath<'_>,
524
    ) -> Option<OwnedObjectPath> {
525
33
        let alias = path.strip_prefix("/org/freedesktop/secrets/aliases/")?;
526
        Self::find_by_alias(collections, alias).await
527
    }
528

            
529
88
    async fn find_by_alias(collections: &[Collection], alias: &str) -> Option<OwnedObjectPath> {
530
63
        let alias_to_find = if alias == Self::LOGIN_ALIAS {
531
            oo7::dbus::Service::DEFAULT_COLLECTION
532
        } else {
533
25
            alias
534
        };
535
69
        for collection in collections {
536
63
            if collection.alias().await == alias_to_find {
537
25
                return Some(collection.path().to_owned().into());
538
            }
539
        }
540
6
        None
541
    }
542

            
543
    #[cfg(test)]
544
16
    pub async fn collection_by_label(&self, label: &str) -> Option<Collection> {
545
8
        let collections = self.collections.lock().await;
546
16
        for collection in collections.values() {
547
12
            if collection.label().await == label {
548
4
                return Some(collection.clone());
549
            }
550
        }
551
        None
552
    }
553

            
554
    /// The collections sorted by path, with the default collection first,
555
    /// so lookups and searches are deterministic across daemon restarts.
556
88
    pub(crate) async fn sorted_collections(&self) -> Vec<Collection> {
557
44
        let collections: Vec<Collection> =
558
            self.collections.lock().await.values().cloned().collect();
559
44
        let mut sorted: Vec<(bool, Collection)> = Vec::with_capacity(collections.len());
560
88
        for collection in collections {
561
94
            let is_default = collection.alias().await == oo7::dbus::Service::DEFAULT_COLLECTION;
562
19
            sorted.push((!is_default, collection));
563
        }
564
75
        sorted.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.path().cmp(b.1.path())));
565
25
        sorted
566
            .into_iter()
567
63
            .map(|(_, collection)| collection)
568
            .collect()
569
    }
570

            
571
72
    pub async fn collection_from_path(&self, path: &ObjectPath<'_>) -> Option<Collection> {
572
55
        if let Some(collection) = self.collections.lock().await.get(path).cloned() {
573
19
            return Some(collection);
574
        }
575
8
        let collections = self.sorted_collections().await;
576
8
        let resolved = Self::resolve_alias(&collections, path).await?;
577
        collections
578
            .into_iter()
579
            .find(|c| c.path().as_str() == resolved.as_str())
580
    }
581

            
582
33
    pub fn session_index(&self) -> u32 {
583
31
        self.session_index.fetch_add(1, Ordering::Relaxed)
584
    }
585

            
586
    /// The sender of a method call
587
30
    pub(crate) fn sender(header: &zbus::message::Header<'_>) -> Option<UniqueName<'static>> {
588
34
        match header.sender() {
589
            Some(sender) => Some(sender.to_owned()),
590
            // p2p test connections don't have a bus to assign unique names
591
            #[cfg(any(test, feature = "test-util"))]
592
            None => Some(UniqueName::from_static_str_unchecked(P2P_TEST_SENDER)),
593
            #[cfg(not(any(test, feature = "test-util")))]
594
            None => None,
595
        }
596
    }
597

            
598
    /// The caller's process, even when it never opened a session
599
58
    pub(crate) async fn peer_info(&self, sender: &UniqueName<'_>) -> Option<PeerInfo> {
600
29
        match self.session_from_sender(sender).await {
601
15
            Some(session) => session.peer_info().cloned(),
602
4
            None => PeerInfo::lookup(&self.connection(), sender).await,
603
        }
604
    }
605

            
606
58
    pub(crate) async fn session_from_sender(&self, sender: &UniqueName<'_>) -> Option<Session> {
607
29
        let sessions = self.sessions.lock().await;
608

            
609
57
        sessions.values().find(|s| s.sender() == sender).cloned()
610
    }
611

            
612
    pub async fn peer_display_name(&self, sender: &UniqueName<'_>) -> String {
613
        match self.session_from_sender(sender).await {
614
            Some(session) => match session.peer_info() {
615
                Some(info) => format!("{sender} ({info})"),
616
                None => sender.to_string(),
617
            },
618
            None => sender.to_string(),
619
        }
620
    }
621

            
622
62
    pub async fn session(&self, path: &ObjectPath<'_>) -> Option<Session> {
623
34
        let session = self.sessions.lock().await.get(path).cloned()?;
624
15
        session.unmark_stale().await;
625
15
        Some(session)
626
    }
627

            
628
24
    pub async fn remove_session(&self, path: &ObjectPath<'_>) {
629
12
        self.sessions.lock().await.remove(path);
630
    }
631

            
632
36
    pub async fn remove_collection(&self, path: &ObjectPath<'_>) {
633
18
        self.collections.lock().await.remove(path);
634

            
635
16
        if let Ok(signal_emitter) =
636
            self.signal_emitter(oo7::dbus::api::Service::PATH.as_deref().unwrap())
637
        {
638
20
            let _ = self.collections_changed(&signal_emitter).await;
639
        }
640
    }
641

            
642
14
    pub fn prompt_index(&self) -> u32 {
643
15
        self.prompt_index.fetch_add(1, Ordering::Relaxed)
644
    }
645

            
646
44
    pub async fn prompt(&self, path: &ObjectPath<'_>) -> Option<Prompt> {
647
22
        self.prompts.lock().await.get(path).cloned()
648
    }
649

            
650
40
    pub async fn remove_prompt(&self, path: &ObjectPath<'_>) {
651
20
        self.prompts.lock().await.remove(path);
652
        // Also clean up pending collection if it exists
653
10
        self.pending_collections.lock().await.remove(path);
654
    }
655

            
656
26
    pub async fn register_prompt(&self, path: OwnedObjectPath, prompt: Prompt) {
657
12
        self.prompts.lock().await.insert(path, prompt);
658
    }
659

            
660
10
    pub async fn pending_collection(
661
        &self,
662
        prompt_path: &ObjectPath<'_>,
663
    ) -> Option<(String, String)> {
664
43
        self.pending_collections
665
            .lock()
666
36
            .await
667
12
            .get(prompt_path)
668
            .cloned()
669
    }
670

            
671
    /// Build a new collection with a unique label/alias, register it on the
672
    /// object server, insert it into the collections map, and emit D-Bus
673
    /// signals.
674
10
    async fn register_collection(
675
        &self,
676
        name: &str,
677
        label: &str,
678
        alias: &str,
679
        keyring: Keyring,
680
    ) -> Result<(OwnedObjectPath, Collection), ServiceError> {
681
11
        let (unique_label, unique_alias) = {
682
22
            let collections = self.collections.lock().await;
683
21
            naming::make_unique_label_and_alias(&collections, label, alias).await
684
        };
685
33
        let collection =
686
            Collection::new(name, &unique_label, &unique_alias, self.clone(), keyring).await;
687
22
        let collection_path: OwnedObjectPath = collection.path().to_owned().into();
688

            
689
58
        self.object_server()
690
22
            .at(collection.path(), collection.clone())
691
40
            .await?;
692
12
        collection.serve_alias_path(&unique_alias).await;
693

            
694
50
        self.collections
695
            .lock()
696
36
            .await
697
24
            .insert(collection_path.clone(), collection.clone());
698

            
699
10
        let service_path = oo7::dbus::api::Service::PATH.as_ref().unwrap();
700
12
        let signal_emitter = self.signal_emitter(service_path)?;
701
22
        Service::collection_created(&signal_emitter, &collection_path).await?;
702
12
        self.collections_changed(&signal_emitter).await?;
703

            
704
10
        tracing::info!("Collection `{collection_path}` created with label '{label}'");
705

            
706
12
        Ok((collection_path, collection))
707
    }
708

            
709
10
    pub async fn create_collection_with_secret(
710
        &self,
711
        label: &str,
712
        alias: &str,
713
        secret: Option<Secret>,
714
    ) -> Result<OwnedObjectPath, ServiceError> {
715
        // Create a persistent keyring with the provided secret
716
72
        let keyring = UnlockedKeyring::open_at(&self.data_dir, &label.to_lowercase(), secret)
717
29
            .await
718
20
            .map_err(|err| custom_service_error(&format!("Failed to create keyring: {err}")))?;
719

            
720
        // Write the keyring file to disk immediately
721
60
        keyring
722
            .write()
723
39
            .await
724
10
            .map_err(|err| custom_service_error(&format!("Failed to write keyring file: {err}")))?;
725

            
726
10
        let name = label.to_lowercase();
727
42
        let (path, _) = self
728
22
            .register_collection(&name, label, alias, Keyring::Unlocked(keyring))
729
58
            .await?;
730
10
        Ok(path)
731
    }
732

            
733
10
    pub async fn complete_collection_creation(
734
        &self,
735
        prompt_path: &ObjectPath<'_>,
736
        secret: Option<Secret>,
737
    ) -> Result<OwnedObjectPath, ServiceError> {
738
21
        let Some((label, alias)) = self.pending_collection(prompt_path).await else {
739
8
            return Err(ServiceError::NoSuchObject(format!(
740
                "No pending collection for prompt `{prompt_path}`"
741
            )));
742
        };
743

            
744
48
        let collection_path = self
745
23
            .create_collection_with_secret(&label, &alias, secret)
746
41
            .await?;
747

            
748
23
        self.pending_collections.lock().await.remove(prompt_path);
749

            
750
11
        Ok(collection_path)
751
    }
752

            
753
68
    pub fn signal_emitter<'a, P>(
754
        &self,
755
        path: P,
756
    ) -> Result<zbus::object_server::SignalEmitter<'a>, oo7::dbus::ServiceError>
757
    where
758
        P: TryInto<ObjectPath<'a>>,
759
        P::Error: Into<zbus::Error>,
760
    {
761
81
        let signal_emitter = zbus::object_server::SignalEmitter::new(&self.connection(), path)?;
762

            
763
65
        Ok(signal_emitter)
764
    }
765
}
766

            
767
#[cfg(test)]
768
mod tests;
769
#[cfg(test)]
770
mod unencrypted_tests;