1
// Backward compatibility interface for GNOME Keyring.
2
// This allows creating/unlocking collections without user prompts.
3

            
4
use oo7::{
5
    Secret,
6
    dbus::{
7
        ServiceError,
8
        api::{DBusSecret, DBusSecretInner, Properties},
9
    },
10
    file::Keyring,
11
};
12
use zbus::wire::{ObjectPath, OwnedObjectPath, OwnedVariant};
13

            
14
use crate::{
15
    error::custom_service_error,
16
    prompt::{Prompt, PromptAction, PromptRole},
17
    service::Service,
18
};
19

            
20
#[derive(Clone)]
21
pub struct InternalInterface {
22
    service: Service,
23
}
24

            
25
impl InternalInterface {
26
4
    pub fn new(service: Service) -> Self {
27
        Self { service }
28
    }
29

            
30
16
    async fn decrypt_secret(&self, secret: DBusSecretInner) -> Result<oo7::Secret, ServiceError> {
31
4
        let session_path = &secret.0;
32

            
33
8
        let Some(session) = self.service.session(session_path).await else {
34
            return Err(ServiceError::NoSession(format!(
35
                "The session `{session_path}` does not exist."
36
            )));
37
        };
38

            
39
24
        let secret = DBusSecret::from_inner(&self.service.connection(), secret)
40
12
            .await
41
4
            .map_err(|err| {
42
                custom_service_error(&format!("Failed to create session object {err}"))
43
            })?;
44

            
45
        secret
46
8
            .decrypt(session.aes_key().as_ref())
47
4
            .map_err(|err| custom_service_error(&format!("Failed to decrypt secret {err}")))
48
    }
49
}
50

            
51
#[zbus::interface(name = "org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface")]
52
impl InternalInterface {
53
    /// Create a collection with a master password without prompting the user.
54
    #[zbus(name = "CreateWithMasterPassword")]
55
4
    async fn create_with_master_password(
56
        &self,
57
        properties: Properties,
58
        master: DBusSecretInner,
59
    ) -> Result<OwnedObjectPath, ServiceError> {
60
8
        let label = properties.label().to_owned();
61
8
        let secret = self.decrypt_secret(master).await?;
62

            
63
16
        let collection_path = self
64
            .service
65
8
            .create_collection_with_secret(&label, "", Some(secret))
66
16
            .await?;
67

            
68
10
        tracing::info!(
69
            "Collection `{}` created with label '{}' via InternalUnsupportedGuiltRiddenInterface",
70
            collection_path,
71
            label
72
        );
73

            
74
4
        Ok(collection_path)
75
    }
76

            
77
    /// Unlock a collection with a master password.
78
    #[zbus(name = "UnlockWithMasterPassword")]
79
4
    async fn unlock_with_master_password(
80
        &self,
81
        collection: ObjectPath<'_>,
82
        master: DBusSecretInner,
83
    ) -> Result<(), ServiceError> {
84
8
        let secret = self.decrypt_secret(master).await?;
85

            
86
20
        let collection_obj = self
87
            .service
88
4
            .collection_from_path(&collection)
89
12
            .await
90
8
            .ok_or_else(|| ServiceError::NoSuchObject(collection.to_string()))?;
91

            
92
20
        self.service
93
4
            .unlock_collection(&collection_obj, Some(secret))
94
20
            .await?;
95

            
96
8
        tracing::info!(
97
            "Collection `{}` unlocked via InternalUnsupportedGuiltRiddenInterface",
98
            collection
99
        );
100

            
101
4
        Ok(())
102
    }
103

            
104
    /// Change collection password with a master password.
105
    #[zbus(name = "ChangeWithMasterPassword")]
106
4
    async fn change_with_master_password(
107
        &self,
108
        collection: ObjectPath<'_>,
109
        original: DBusSecretInner,
110
        master: DBusSecretInner,
111
    ) -> Result<(), ServiceError> {
112
8
        let original_secret = self.decrypt_secret(original).await?;
113
8
        let new_secret = self.decrypt_secret(master).await?;
114

            
115
20
        let collection_obj = self
116
            .service
117
4
            .collection_from_path(&collection)
118
12
            .await
119
8
            .ok_or_else(|| ServiceError::NoSuchObject(collection.to_string()))?;
120

            
121
16
        self.service
122
4
            .unlock_collection(&collection_obj, Some(original_secret))
123
16
            .await?;
124

            
125
4
        let keyring_guard = collection_obj.keyring.read().await;
126
12
        if let Some(Keyring::Unlocked(unlocked)) = keyring_guard.as_ref() {
127
16
            unlocked
128
4
                .change_secret(new_secret)
129
16
                .await
130
4
                .map_err(|err| custom_service_error(&format!("Failed to change secret: {err}")))?;
131
        } else {
132
            return Err(custom_service_error("Collection is not unlocked"));
133
        }
134

            
135
8
        tracing::info!(
136
            "Collection `{}` password changed via InternalUnsupportedGuiltRiddenInterface",
137
            collection
138
        );
139

            
140
4
        Ok(())
141
    }
142

            
143
    /// Change collection password with a prompt.
144
    #[zbus(name = "ChangeWithPrompt")]
145
4
    async fn change_with_prompt(
146
        &self,
147
        collection: ObjectPath<'_>,
148
    ) -> Result<OwnedObjectPath, ServiceError> {
149
20
        let collection_obj = self
150
            .service
151
4
            .collection_from_path(&collection)
152
12
            .await
153
8
            .ok_or_else(|| ServiceError::NoSuchObject(collection.to_string()))?;
154

            
155
8
        let label = collection_obj.label().await;
156

            
157
        let prompt = Prompt::new(
158
8
            self.service.clone(),
159
            PromptRole::ChangePassword,
160
4
            label,
161
8
            Some(collection_obj.clone()),
162
        )
163
12
        .await;
164
8
        let prompt_path: OwnedObjectPath = prompt.path().to_owned().into();
165

            
166
8
        let service = self.service.clone();
167
4
        let collection_path = collection.to_owned();
168
8
        let action = PromptAction::new(move |new_secret: Option<Secret>| {
169
4
            let service = service.clone();
170
4
            let collection_path = collection_path.clone();
171
16
            async move {
172
20
                let collection = service
173
4
                    .collection_from_path(&collection_path)
174
12
                    .await
175
4
                    .ok_or_else(|| ServiceError::NoSuchObject(collection_path.to_string()))?;
176

            
177
8
                let keyring_guard = collection.keyring.read().await;
178
12
                if let Some(Keyring::Unlocked(unlocked)) = keyring_guard.as_ref() {
179
4
                    if let Some(new_secret) = new_secret {
180
13
                        unlocked.change_secret(new_secret).await.map_err(|err| {
181
                            custom_service_error(&format!("Failed to change secret: {err}"))
182
                        })?;
183
                    } else {
184
8
                        return Err(custom_service_error(
185
                            "Cannot change to empty password via this interface",
186
                        ));
187
                    }
188
                } else {
189
                    return Err(custom_service_error(
190
                        "Collection must be unlocked to change password",
191
                    ));
192
                }
193

            
194
8
                tracing::info!(
195
                    "Collection `{}` password changed via prompt",
196
                    collection_path
197
                );
198

            
199
8
                Ok(OwnedVariant::from(ObjectPath::from_str_unchecked("/")))
200
            }
201
        });
202

            
203
4
        prompt.set_action(action).await;
204

            
205
20
        self.service
206
            .object_server()
207
8
            .at(prompt.path(), prompt.clone())
208
16
            .await?;
209

            
210
8
        self.service
211
4
            .register_prompt(prompt_path.clone(), prompt)
212
8
            .await;
213

            
214
8
        tracing::info!(
215
            "Created password change prompt for collection `{}`",
216
            collection
217
        );
218

            
219
4
        Ok(prompt_path)
220
    }
221
}
222

            
223
#[cfg(test)]
224
mod tests {
225
    use oo7::{Secret, dbus};
226
    use zbus::wire::{ObjectPath, OwnedObjectPath};
227

            
228
    use crate::tests::{TestServiceSetup, pending_migration_setup};
229

            
230
    /// Proxy for the InternalUnsupportedGuiltRiddenInterface
231
    #[zbus::proxy(
232
        interface = "org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface",
233
        default_service = "org.freedesktop.secrets",
234
        default_path = "/org/freedesktop/secrets"
235
    )]
236
    trait InternalInterfaceProxy {
237
        #[zbus(name = "CreateWithMasterPassword")]
238
        fn create_with_master_password(
239
            &self,
240
            properties: dbus::api::Properties,
241
            master: dbus::api::DBusSecretInner,
242
        ) -> zbus::Result<OwnedObjectPath>;
243

            
244
        #[zbus(name = "UnlockWithMasterPassword")]
245
        fn unlock_with_master_password(
246
            &self,
247
            collection: &ObjectPath<'_>,
248
            master: dbus::api::DBusSecretInner,
249
        ) -> zbus::Result<()>;
250

            
251
        #[zbus(name = "ChangeWithMasterPassword")]
252
        fn change_with_master_password(
253
            &self,
254
            collection: &ObjectPath<'_>,
255
            original: dbus::api::DBusSecretInner,
256
            master: dbus::api::DBusSecretInner,
257
        ) -> zbus::Result<()>;
258

            
259
        #[zbus(name = "ChangeWithPrompt")]
260
        fn change_with_prompt(&self, collection: &ObjectPath<'_>) -> zbus::Result<OwnedObjectPath>;
261
    }
262

            
263
    #[tokio::test]
264
    async fn test_create_with_master_password() -> Result<(), Box<dyn std::error::Error>> {
265
        let setup = TestServiceSetup::encrypted_session(false).await?;
266

            
267
        // Create proxy to the InternalInterface
268
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
269
            .build()
270
            .await?;
271

            
272
        // Prepare properties for collection creation
273
        let label = "TestCollection";
274
        let properties = oo7::dbus::api::Properties::for_collection(label);
275

            
276
        // Prepare the master password secret
277
        let dbus_secret = setup.create_dbus_secret("my-master-password")?;
278
        let dbus_secret_inner = dbus_secret.into();
279

            
280
        // Call CreateWithMasterPassword via D-Bus
281
        let collection_path = internal_proxy
282
            .create_with_master_password(properties, dbus_secret_inner)
283
            .await?;
284

            
285
        // Verify the collection was created
286
        assert!(
287
            !collection_path.as_str().is_empty(),
288
            "Collection path should not be empty"
289
        );
290

            
291
        // Verify we can access the newly created collection via D-Bus
292
        let collection =
293
            oo7::dbus::api::Collection::new(&setup.client_conn, collection_path.clone()).await?;
294
        let label = collection.label().await?;
295
        assert_eq!(
296
            label, "TestCollection",
297
            "Collection should have the correct label"
298
        );
299
        Ok(())
300
    }
301

            
302
    #[tokio::test]
303
    async fn test_unlock_with_master_password() -> Result<(), Box<dyn std::error::Error>> {
304
        let setup = TestServiceSetup::encrypted_session(true).await?;
305
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
306
            .build()
307
            .await?;
308

            
309
        // Get the default collection
310
        let default_collection = &setup.collections[0];
311
        let collection_path: zbus::wire::OwnedObjectPath =
312
            default_collection.inner().path().to_owned().into();
313

            
314
        // Lock the collection
315
        setup
316
            .service_api
317
            .lock(std::slice::from_ref(&collection_path), None)
318
            .await?;
319

            
320
        // Verify it's locked
321
        assert!(
322
            default_collection.is_locked().await?,
323
            "Collection should be locked"
324
        );
325

            
326
        // Prepare the unlock secret (use the keyring secret)
327
        let unlock_secret = setup.keyring_secret.clone().unwrap();
328
        let dbus_secret = setup.create_dbus_secret(unlock_secret)?;
329
        let dbus_secret_inner = dbus_secret.into();
330

            
331
        // Call UnlockWithMasterPassword via D-Bus
332
        internal_proxy
333
            .unlock_with_master_password(&collection_path.as_ref(), dbus_secret_inner)
334
            .await?;
335

            
336
        // Verify it's unlocked
337
        assert!(
338
            !default_collection.is_locked().await?,
339
            "Collection should be unlocked"
340
        );
341

            
342
        Ok(())
343
    }
344

            
345
    #[tokio::test]
346
    async fn test_change_with_master_password() -> Result<(), Box<dyn std::error::Error>> {
347
        let setup = TestServiceSetup::encrypted_session(true).await?;
348
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
349
            .build()
350
            .await?;
351

            
352
        let default_collection = &setup.collections[0];
353
        let collection_path: zbus::wire::OwnedObjectPath =
354
            default_collection.inner().path().to_owned().into();
355

            
356
        // Prepare original and new secrets
357
        let original_secret = setup.keyring_secret.clone().unwrap();
358
        let new_secret = Secret::text("new-master-password");
359

            
360
        let original_dbus = setup.create_dbus_secret(original_secret)?;
361
        let new_dbus = setup.create_dbus_secret(new_secret.clone())?;
362

            
363
        // Call ChangeWithMasterPassword via D-Bus
364
        internal_proxy
365
            .change_with_master_password(
366
                &collection_path.as_ref(),
367
                original_dbus.into(),
368
                new_dbus.into(),
369
            )
370
            .await?;
371

            
372
        // Verify the password was changed by locking and unlocking with new
373
        // password
374
        setup
375
            .service_api
376
            .lock(std::slice::from_ref(&collection_path), None)
377
            .await?;
378
        assert!(
379
            default_collection.is_locked().await?,
380
            "Collection should be locked"
381
        );
382

            
383
        // Unlock with new password via D-Bus
384
        let unlock_dbus = setup.create_dbus_secret(new_secret)?;
385
        internal_proxy
386
            .unlock_with_master_password(&collection_path.as_ref(), unlock_dbus.into())
387
            .await?;
388

            
389
        assert!(
390
            !default_collection.is_locked().await?,
391
            "Collection should be unlocked with new password"
392
        );
393

            
394
        Ok(())
395
    }
396

            
397
    #[tokio::test]
398
    async fn test_change_with_prompt() -> Result<(), Box<dyn std::error::Error>> {
399
        let setup = TestServiceSetup::encrypted_session(true).await?;
400
        setup.set_password_accept(true).await;
401

            
402
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
403
            .build()
404
            .await?;
405

            
406
        let default_collection = &setup.collections[0];
407
        let collection_path: zbus::wire::OwnedObjectPath =
408
            default_collection.inner().path().to_owned().into();
409

            
410
        // Call ChangeWithPrompt via D-Bus
411
        let prompt_path = internal_proxy
412
            .change_with_prompt(&collection_path.as_ref())
413
            .await?;
414

            
415
        // Verify prompt was created
416
        assert!(
417
            !prompt_path.as_str().is_empty(),
418
            "Prompt path should not be empty"
419
        );
420

            
421
        // Get the prompt and complete it
422
        let prompt_proxy = dbus::api::Prompt::new(&setup.client_conn, prompt_path)
423
            .await?
424
            .unwrap();
425
        let new_password = Secret::text("new-password-from-prompt");
426
        setup.set_password_queue(vec![new_password.clone()]).await;
427

            
428
        prompt_proxy.prompt(None).await?;
429

            
430
        // Wait for prompt to complete
431
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
432

            
433
        // Verify the password was changed by locking and unlocking with new
434
        // password
435
        setup
436
            .service_api
437
            .lock(std::slice::from_ref(&collection_path), None)
438
            .await?;
439
        assert!(
440
            default_collection.is_locked().await?,
441
            "Collection should be locked"
442
        );
443

            
444
        // Unlock with new password via D-Bus
445
        let unlock_dbus = setup.create_dbus_secret(new_password)?;
446
        internal_proxy
447
            .unlock_with_master_password(&collection_path.as_ref(), unlock_dbus.into())
448
            .await?;
449

            
450
        assert!(
451
            !default_collection.is_locked().await?,
452
            "Collection should be unlocked with new password"
453
        );
454

            
455
        Ok(())
456
    }
457

            
458
    // https://github.com/linux-credentials/oo7/issues/696
459
    #[tokio::test]
460
    async fn test_change_with_prompt_pending_migration() -> Result<(), Box<dyn std::error::Error>> {
461
        let (setup, _temp_dir, collection_path) = pending_migration_setup(None).await?;
462
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
463
            .build()
464
            .await?;
465

            
466
        let collection =
467
            oo7::dbus::api::Collection::new(&setup.client_conn, collection_path.clone()).await?;
468
        assert!(collection.is_locked().await?);
469

            
470
        // Queue: old password first (to unlock and migrate), then the new
471
        // password (to change to)
472
        let new_password = Secret::text("changed-via-prompt");
473
        setup
474
            .set_password_queue(vec![Secret::from("test"), new_password.clone()])
475
            .await;
476

            
477
        let prompt_path = internal_proxy
478
            .change_with_prompt(&collection_path.as_ref())
479
            .await?;
480
        let prompt_proxy = dbus::api::Prompt::new(&setup.client_conn, prompt_path)
481
            .await?
482
            .unwrap();
483
        prompt_proxy.receive_completed(None).await?;
484

            
485
        // The migration completed and the keyring holds its items
486
        assert_eq!(setup.server.pending_migrations.lock().await.len(), 0);
487
        assert!(!collection.is_locked().await?);
488
        assert_eq!(collection.items().await?.len(), 1);
489
        assert_eq!(collection.items().await?[0].label().await?, "foo");
490

            
491
        // The keyring now opens with the new password, not the old one
492
        setup
493
            .service_api
494
            .lock(std::slice::from_ref(&collection_path), None)
495
            .await?;
496
        internal_proxy
497
            .unlock_with_master_password(
498
                &collection_path.as_ref(),
499
                setup.create_dbus_secret(new_password)?.into(),
500
            )
501
            .await?;
502
        assert!(!collection.is_locked().await?);
503
        setup
504
            .service_api
505
            .lock(std::slice::from_ref(&collection_path), None)
506
            .await?;
507
        let result = internal_proxy
508
            .unlock_with_master_password(
509
                &collection_path.as_ref(),
510
                setup.create_dbus_secret("test")?.into(),
511
            )
512
            .await;
513
        assert!(result.is_err(), "The old password should no longer unlock");
514

            
515
        Ok(())
516
    }
517

            
518
    #[tokio::test]
519
    async fn test_change_with_prompt_locked_collection() -> Result<(), Box<dyn std::error::Error>> {
520
        let setup = TestServiceSetup::plain_session(true).await?;
521
        setup.set_password_accept(true).await;
522

            
523
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
524
            .build()
525
            .await?;
526

            
527
        let default_collection = &setup.collections[0];
528
        let collection_path: zbus::wire::OwnedObjectPath =
529
            default_collection.inner().path().to_owned().into();
530

            
531
        // Create an item so that unlock validation has something to check
532
        let dbus_secret = setup.create_dbus_secret("item-secret")?;
533
        default_collection
534
            .create_item(
535
                "Test Item",
536
                &[("test-change", "locked")],
537
                &dbus_secret,
538
                false,
539
                None,
540
            )
541
            .await?;
542

            
543
        // Lock the collection
544
        setup
545
            .service_api
546
            .lock(std::slice::from_ref(&collection_path), None)
547
            .await?;
548
        assert!(
549
            default_collection.is_locked().await?,
550
            "Collection should be locked"
551
        );
552

            
553
        // Queue: old password first (to unlock), then new password (to change
554
        // to)
555
        let old_password = setup.keyring_secret.clone().unwrap();
556
        let new_password = Secret::text("changed-via-locked-prompt");
557
        setup
558
            .set_password_queue(vec![old_password, new_password.clone()])
559
            .await;
560

            
561
        // Call ChangeWithPrompt on the locked collection
562
        let prompt_path = internal_proxy
563
            .change_with_prompt(&collection_path.as_ref())
564
            .await?;
565

            
566
        let prompt_proxy = dbus::api::Prompt::new(&setup.client_conn, prompt_path)
567
            .await?
568
            .unwrap();
569

            
570
        // Wait for the multi-step prompt to complete via the Completed signal
571
        prompt_proxy.receive_completed(None).await?;
572

            
573
        // Collection should now be unlocked (old password step unlocked it)
574
        assert!(
575
            !default_collection.is_locked().await?,
576
            "Collection should be unlocked after prompt"
577
        );
578

            
579
        // Verify the password was changed: lock, then unlock with new password
580
        setup
581
            .service_api
582
            .lock(std::slice::from_ref(&collection_path), None)
583
            .await?;
584
        assert!(
585
            default_collection.is_locked().await?,
586
            "Collection should be locked"
587
        );
588

            
589
        let unlock_dbus = setup.create_dbus_secret(new_password)?;
590
        internal_proxy
591
            .unlock_with_master_password(&collection_path.as_ref(), unlock_dbus.into())
592
            .await?;
593

            
594
        assert!(
595
            !default_collection.is_locked().await?,
596
            "Collection should be unlocked with new password"
597
        );
598

            
599
        Ok(())
600
    }
601

            
602
    #[tokio::test]
603
    async fn test_change_with_prompt_wrong_old_password() -> Result<(), Box<dyn std::error::Error>>
604
    {
605
        let old_password = Secret::text("test-password-long-enough");
606
        let setup = TestServiceSetup::with_login_keyring(old_password.clone()).await?;
607
        setup.set_password_accept(true).await;
608

            
609
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
610
            .build()
611
            .await?;
612

            
613
        let default_collection = &setup.collections[0];
614
        let collection_path: zbus::wire::OwnedObjectPath =
615
            default_collection.inner().path().to_owned().into();
616

            
617
        // Create an item so that unlock validation has something to check
618
        let dbus_secret = setup.create_dbus_secret("item-secret")?;
619
        default_collection
620
            .create_item(
621
                "Test Item",
622
                &[("test-change", "retry")],
623
                &dbus_secret,
624
                false,
625
                None,
626
            )
627
            .await?;
628

            
629
        // Lock the collection (disk-backed so wrong password retries work)
630
        setup
631
            .service_api
632
            .lock(std::slice::from_ref(&collection_path), None)
633
            .await?;
634

            
635
        // Queue: wrong password first, then correct old password, then new
636
        // password
637
        let new_password = Secret::text("changed-after-retry");
638
        setup
639
            .set_password_queue(vec![
640
                Secret::text("wrong-password"),
641
                old_password,
642
                new_password.clone(),
643
            ])
644
            .await;
645

            
646
        let prompt_path = internal_proxy
647
            .change_with_prompt(&collection_path.as_ref())
648
            .await?;
649

            
650
        let prompt_proxy = dbus::api::Prompt::new(&setup.client_conn, prompt_path)
651
            .await?
652
            .unwrap();
653

            
654
        // Wait for multi-step prompt with retry to complete
655
        prompt_proxy.receive_completed(None).await?;
656

            
657
        // Verify the password was changed
658
        setup
659
            .service_api
660
            .lock(std::slice::from_ref(&collection_path), None)
661
            .await?;
662

            
663
        let unlock_dbus = setup.create_dbus_secret(new_password)?;
664
        internal_proxy
665
            .unlock_with_master_password(&collection_path.as_ref(), unlock_dbus.into())
666
            .await?;
667

            
668
        assert!(
669
            !default_collection.is_locked().await?,
670
            "Collection should be unlocked with new password after retry"
671
        );
672

            
673
        Ok(())
674
    }
675

            
676
    #[tokio::test]
677
    async fn test_change_with_prompt_error_emits_dismissed()
678
    -> Result<(), Box<dyn std::error::Error>> {
679
        let setup = TestServiceSetup::encrypted_session(true).await?;
680
        setup.set_password_accept(true).await;
681

            
682
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
683
            .build()
684
            .await?;
685

            
686
        let default_collection = &setup.collections[0];
687
        let collection_path: zbus::wire::OwnedObjectPath =
688
            default_collection.inner().path().to_owned().into();
689

            
690
        // Queue an empty password — the action rejects empty passwords
691
        setup.set_password_queue(vec![Secret::from("")]).await;
692

            
693
        let prompt_path = internal_proxy
694
            .change_with_prompt(&collection_path.as_ref())
695
            .await?;
696

            
697
        let prompt_proxy = dbus::api::Prompt::new(&setup.client_conn, prompt_path)
698
            .await?
699
            .unwrap();
700

            
701
        // The action will fail, which should emit Completed(dismissed=true).
702
        let result = prompt_proxy.receive_completed(None).await;
703

            
704
        assert!(
705
            matches!(result, Err(dbus::Error::Dismissed)),
706
            "Failed prompt action should emit Completed(dismissed=true), got: {result:?}"
707
        );
708

            
709
        Ok(())
710
    }
711

            
712
    // https://github.com/linux-credentials/oo7/issues/689
713
    #[tokio::test]
714
    async fn test_unlock_with_master_password_pending_migration()
715
    -> Result<(), Box<dyn std::error::Error>> {
716
        let (setup, _temp_dir, collection_path) = pending_migration_setup(None).await?;
717
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
718
            .build()
719
            .await?;
720

            
721
        let collection =
722
            oo7::dbus::api::Collection::new(&setup.client_conn, collection_path.clone()).await?;
723
        assert!(collection.is_locked().await?);
724
        // The placeholder only exposes the locked stand-in item
725
        assert_eq!(collection.items().await?.len(), 1);
726
        assert!(collection.items().await?[0].is_locked().await?);
727

            
728
        let dbus_secret = setup.create_dbus_secret("test")?;
729
        internal_proxy
730
            .unlock_with_master_password(&collection_path.as_ref(), dbus_secret.into())
731
            .await?;
732

            
733
        assert!(!collection.is_locked().await?);
734
        assert_eq!(collection.items().await?.len(), 1);
735
        assert!(!collection.items().await?[0].is_locked().await?);
736
        assert_eq!(collection.items().await?[0].label().await?, "foo");
737
        assert_eq!(setup.server.pending_migrations.lock().await.len(), 0);
738

            
739
        Ok(())
740
    }
741

            
742
    // https://github.com/linux-credentials/oo7/issues/689
743
    #[tokio::test]
744
    async fn test_unlock_with_master_password_pending_migration_wrong_password()
745
    -> Result<(), Box<dyn std::error::Error>> {
746
        let (setup, _temp_dir, collection_path) = pending_migration_setup(None).await?;
747
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
748
            .build()
749
            .await?;
750

            
751
        let collection =
752
            oo7::dbus::api::Collection::new(&setup.client_conn, collection_path.clone()).await?;
753

            
754
        let wrong_dbus_secret = setup.create_dbus_secret("wrong-password")?;
755
        let result = internal_proxy
756
            .unlock_with_master_password(&collection_path.as_ref(), wrong_dbus_secret.into())
757
            .await;
758

            
759
        assert!(result.is_err(), "Unlocking with wrong password should fail");
760
        assert!(collection.is_locked().await?);
761
        assert_eq!(
762
            setup.server.pending_migrations.lock().await.len(),
763
            1,
764
            "Migration should still be pending"
765
        );
766

            
767
        Ok(())
768
    }
769

            
770
    // https://github.com/linux-credentials/oo7/issues/689
771
    #[tokio::test]
772
    async fn test_change_with_master_password_pending_migration()
773
    -> Result<(), Box<dyn std::error::Error>> {
774
        let (setup, _temp_dir, collection_path) = pending_migration_setup(None).await?;
775
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
776
            .build()
777
            .await?;
778

            
779
        let collection =
780
            oo7::dbus::api::Collection::new(&setup.client_conn, collection_path.clone()).await?;
781

            
782
        let new_secret = Secret::text("new-master-password");
783
        internal_proxy
784
            .change_with_master_password(
785
                &collection_path.as_ref(),
786
                setup.create_dbus_secret("test")?.into(),
787
                setup.create_dbus_secret(new_secret.clone())?.into(),
788
            )
789
            .await?;
790

            
791
        // The keyring is migrated and unlocked with its items
792
        assert!(!collection.is_locked().await?);
793
        assert_eq!(collection.items().await?.len(), 1);
794
        assert_eq!(setup.server.pending_migrations.lock().await.len(), 0);
795

            
796
        // The migrated keyring now opens with the new master password
797
        setup
798
            .service_api
799
            .lock(std::slice::from_ref(&collection_path), None)
800
            .await?;
801
        assert!(collection.is_locked().await?);
802

            
803
        internal_proxy
804
            .unlock_with_master_password(
805
                &collection_path.as_ref(),
806
                setup.create_dbus_secret(new_secret)?.into(),
807
            )
808
            .await?;
809
        assert!(!collection.is_locked().await?);
810

            
811
        Ok(())
812
    }
813

            
814
    #[tokio::test]
815
    async fn test_unlock_with_wrong_password() -> Result<(), Box<dyn std::error::Error>> {
816
        let setup = TestServiceSetup::encrypted_session(true).await?;
817
        let internal_proxy = InternalInterfaceProxyProxy::builder(&setup.client_conn)
818
            .build()
819
            .await?;
820

            
821
        let default_collection = &setup.collections[0];
822
        let collection_path: zbus::wire::OwnedObjectPath =
823
            default_collection.inner().path().to_owned().into();
824

            
825
        // Create an item first so that the unlock validation has something to
826
        // validate
827
        let dbus_secret = setup.create_dbus_secret("item-secret")?;
828

            
829
        let mut attributes = std::collections::HashMap::new();
830
        attributes.insert("test".to_string(), "value".to_string());
831

            
832
        default_collection
833
            .create_item("Test Item", &attributes, &dbus_secret, false, None)
834
            .await?;
835

            
836
        // Lock the collection
837
        setup
838
            .service_api
839
            .lock(std::slice::from_ref(&collection_path), None)
840
            .await?;
841

            
842
        // Verify it's locked before attempting unlock
843
        assert!(
844
            default_collection.is_locked().await?,
845
            "Collection should be locked before unlock attempt"
846
        );
847

            
848
        // Try to unlock with wrong password via D-Bus
849
        let wrong_dbus_secret = setup.create_dbus_secret("wrong-password")?;
850

            
851
        let result = internal_proxy
852
            .unlock_with_master_password(&collection_path.as_ref(), wrong_dbus_secret.into())
853
            .await;
854

            
855
        // Should fail
856
        assert!(result.is_err(), "Unlocking with wrong password should fail");
857

            
858
        // Collection should remain locked
859
        assert!(
860
            default_collection.is_locked().await?,
861
            "Collection should remain locked after failed unlock"
862
        );
863

            
864
        Ok(())
865
    }
866
}