1
use std::sync::{
2
    Arc,
3
    atomic::{AtomicBool, AtomicU32, Ordering},
4
};
5

            
6
use formatx::formatx;
7
use gettextrs::gettext;
8
use oo7::{Key, ashpd::WindowIdentifierType, dbus::ServiceError};
9
use serde::{Deserialize, Serialize};
10
use tokio::sync::OnceCell;
11
use zbus::wire::{self, ObjectPath, Optional, OwnedObjectPath, Type, Variant, as_variant};
12

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

            
20
/// Custom serde module to handle GCR's double-Variant wrapping bug
21
///
22
/// See: https://gitlab.gnome.org/GNOME/gcr/-/merge_requests/169
23
mod double_value_optional {
24
    use super::*;
25

            
26
4
    fn unwrap_double_value<'de>(outer_value: Variant<'de>) -> Result<Variant<'de>, String> {
27
8
        match outer_value.downcast_ref::<Variant>() {
28
8
            Ok(_) => outer_value
29
                .downcast::<Variant>()
30
4
                .map_err(|e| format!("Failed to unwrap double-wrapped Variant: {e}")),
31
            Err(_) => Ok(outer_value),
32
        }
33
    }
34

            
35
12
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
36
    where
37
        D: serde::Deserializer<'de>,
38
        T: TryFrom<Variant<'de>> + wire::Type,
39
        T::Error: std::fmt::Display,
40
    {
41
12
        let outer_value = Variant::deserialize(deserializer)?;
42
24
        let value_to_deserialize =
43
            unwrap_double_value(outer_value).map_err(serde::de::Error::custom)?;
44

            
45
24
        match T::try_from(value_to_deserialize) {
46
13
            Ok(val) => Ok(Some(val)),
47
            Err(_) => Ok(None),
48
        }
49
    }
50

            
51
    pub fn deserialize_window_id<'de, D>(
52
        deserializer: D,
53
    ) -> Result<Option<WindowIdentifierType>, D::Error>
54
    where
55
        D: serde::Deserializer<'de>,
56
    {
57
        let outer_value = Variant::deserialize(deserializer)?;
58
        let value = unwrap_double_value(outer_value).map_err(serde::de::Error::custom)?;
59

            
60
        match String::try_from(value) {
61
            Ok(s) if !s.is_empty() => Ok(std::str::FromStr::from_str(&s).ok()),
62
            _ => Ok(None),
63
        }
64
    }
65
}
66

            
67
#[derive(Serialize, Deserialize, Type, Default)]
68
#[zbus(signature = "dict")]
69
#[serde(rename_all = "kebab-case")]
70
// GcrPrompt properties <https://gitlab.gnome.org/GNOME/gcr/-/blob/main/gcr/gcr-prompt.c#L95>
71
pub struct Properties {
72
    #[serde(
73
        serialize_with = "as_variant::optional::serialize",
74
        deserialize_with = "double_value_optional::deserialize",
75
        skip_serializing_if = "Option::is_none",
76
        default
77
    )]
78
    title: Option<String>,
79
    #[serde(
80
        serialize_with = "as_variant::optional::serialize",
81
        deserialize_with = "double_value_optional::deserialize",
82
        skip_serializing_if = "Option::is_none",
83
        default
84
    )]
85
    message: Option<String>,
86
    #[serde(
87
        serialize_with = "as_variant::optional::serialize",
88
        deserialize_with = "double_value_optional::deserialize",
89
        skip_serializing_if = "Option::is_none",
90
        default
91
    )]
92
    description: Option<String>,
93
    #[serde(
94
        serialize_with = "as_variant::optional::serialize",
95
        deserialize_with = "double_value_optional::deserialize",
96
        skip_serializing_if = "Option::is_none",
97
        default
98
    )]
99
    warning: Option<String>,
100
    #[serde(
101
        serialize_with = "as_variant::optional::serialize",
102
        deserialize_with = "double_value_optional::deserialize",
103
        skip_serializing_if = "Option::is_none",
104
        default
105
    )]
106
    password_new: Option<bool>,
107
    #[serde(
108
        serialize_with = "as_variant::optional::serialize",
109
        deserialize_with = "double_value_optional::deserialize",
110
        skip_serializing_if = "Option::is_none",
111
        default
112
    )]
113
    password_strength: Option<i32>,
114
    #[serde(
115
        serialize_with = "as_variant::optional::serialize",
116
        deserialize_with = "double_value_optional::deserialize",
117
        skip_serializing_if = "Option::is_none",
118
        default
119
    )]
120
    choice_label: Option<String>,
121
    #[serde(
122
        serialize_with = "as_variant::optional::serialize",
123
        deserialize_with = "double_value_optional::deserialize",
124
        skip_serializing_if = "Option::is_none",
125
        default
126
    )]
127
    choice_chosen: Option<bool>,
128
    #[serde(
129
        serialize_with = "as_variant::optional::serialize",
130
        deserialize_with = "double_value_optional::deserialize_window_id",
131
        skip_serializing_if = "Option::is_none",
132
        default
133
    )]
134
    caller_window: Option<WindowIdentifierType>,
135
    #[serde(
136
        serialize_with = "as_variant::optional::serialize",
137
        deserialize_with = "double_value_optional::deserialize",
138
        skip_serializing_if = "Option::is_none",
139
        default
140
    )]
141
    continue_label: Option<String>,
142
    #[serde(
143
        serialize_with = "as_variant::optional::serialize",
144
        deserialize_with = "double_value_optional::deserialize",
145
        skip_serializing_if = "Option::is_none",
146
        default
147
    )]
148
    cancel_label: Option<String>,
149
}
150

            
151
impl Properties {
152
4
    fn for_change_password_old(
153
        keyring: &str,
154
        warning: Option<&str>,
155
        window_id: Option<&WindowIdentifierType>,
156
    ) -> Self {
157
        Self {
158
4
            title: Some(gettext("Change Keyring Password")),
159
4
            message: Some(
160
                formatx!(gettext("Enter the old password for the “{}” keyring"), keyring)
161
                    .expect("Wrong format in translatable string"),
162
            ),
163
4
            description: Some(
164
                formatx!(
165
                    gettext("An application wants to change the password for the “{}” keyring. Enter the old password for it."),
166
                    keyring,
167
                )
168
                .expect("Wrong format in translatable string"),
169
            ),
170
4
            warning: warning.map(ToOwned::to_owned),
171
            password_new: None,
172
            password_strength: None,
173
            choice_label: None,
174
            choice_chosen: None,
175
4
            caller_window: window_id.map(ToOwned::to_owned),
176
8
            continue_label: Some(gettext("Continue")),
177
8
            cancel_label: Some(gettext("Cancel")),
178
        }
179
    }
180

            
181
4
    fn for_change_password_new(keyring: &str, window_id: Option<&WindowIdentifierType>) -> Self {
182
        Self {
183
4
            title: Some(gettext("Change Keyring Password")),
184
4
            message: Some(
185
                formatx!(gettext("Choose a new password for the “{}” keyring"), keyring)
186
                    .expect("Wrong format in translatable string"),
187
            ),
188
4
            description: Some(
189
                formatx!(
190
                    gettext("An application wants to change the password for the “{}” keyring. Choose the new password you want to use for it."),
191
                    keyring,
192
                )
193
                .expect("Wrong format in translatable string"),
194
            ),
195
8
            warning: Some(gettext("This operation cannot be reverted")),
196
            password_new: Some(true),
197
            password_strength: None,
198
            choice_label: None,
199
            choice_chosen: None,
200
4
            caller_window: window_id.map(ToOwned::to_owned),
201
8
            continue_label: Some(gettext("Continue")),
202
8
            cancel_label: Some(gettext("Cancel")),
203
        }
204
    }
205

            
206
6
    fn for_unlock(
207
        keyring: &str,
208
        warning: Option<&str>,
209
        window_id: Option<&WindowIdentifierType>,
210
    ) -> Self {
211
        Self {
212
6
            title: Some(gettext("Unlock Keyring")),
213
10
            message: Some(gettext("Authentication required")),
214
4
            description: Some(
215
                formatx!(
216
                    gettext("An application wants access to the keyring “{}”, but it is locked",),
217
                    keyring,
218
                )
219
                .expect("Wrong format in translatable string"),
220
            ),
221
4
            warning: warning.map(ToOwned::to_owned),
222
            password_new: None,
223
            password_strength: None,
224
            choice_label: None,
225
            choice_chosen: None,
226
4
            caller_window: window_id.map(ToOwned::to_owned),
227
8
            continue_label: Some(gettext("Unlock")),
228
8
            cancel_label: Some(gettext("Cancel")),
229
        }
230
    }
231

            
232
4
    fn for_create_collection(label: &str, window_id: Option<&WindowIdentifierType>) -> Self {
233
        Self {
234
4
            title: Some(gettext("New Keyring Password")),
235
8
            message: Some(gettext("Choose password for new keyring")),
236
4
            description: Some(
237
                formatx!(
238
                    gettext("An application wants to create a new keyring called “{}”. Choose the password you want to use for it."),
239
                    label
240
                )
241
                .expect("Wrong format in translatable string")
242
            ),
243
            warning: None,
244
            password_new: Some(true),
245
            password_strength: None,
246
            choice_label: None,
247
            choice_chosen: None,
248
4
            caller_window: window_id.map(ToOwned::to_owned),
249
8
            continue_label: Some(gettext("Create")),
250
8
            cancel_label: Some(gettext("Cancel")),
251
        }
252
    }
253
}
254

            
255
#[derive(Deserialize, Serialize, Debug, Type)]
256
#[serde(rename_all = "lowercase")]
257
#[zbus(signature = "s")]
258
pub enum Reply {
259
    No,
260
    Yes,
261
}
262

            
263
impl wire::NoneValue for Reply {
264
    type NoneType = String;
265

            
266
6
    fn null_value() -> Self::NoneType {
267
6
        String::new()
268
    }
269
}
270

            
271
impl TryFrom<String> for Reply {
272
    type Error = String;
273

            
274
6
    fn try_from(value: String) -> Result<Self, Self::Error> {
275
12
        match value.as_str() {
276
10
            "no" => Ok(Reply::No),
277
17
            "yes" => Ok(Reply::Yes),
278
            _ => Err("Invalid value".to_string()),
279
        }
280
    }
281
}
282

            
283
#[derive(Debug, Deserialize, Serialize, Type, PartialEq, Eq, PartialOrd, Ord)]
284
#[serde(rename_all = "lowercase")]
285
#[zbus(signature = "s")]
286
pub enum PromptType {
287
    Confirm,
288
    Password,
289
}
290

            
291
#[zbus::proxy(
292
    default_service = "org.gnome.keyring.SystemPrompter",
293
    interface = "org.gnome.keyring.internal.Prompter",
294
    default_path = "/org/gnome/keyring/Prompter"
295
)]
296
pub trait GNOMEPrompter {
297
    fn begin_prompting(&self, callback: &ObjectPath<'_>) -> Result<(), ServiceError>;
298

            
299
    fn perform_prompt(
300
        &self,
301
        callback: &ObjectPath<'_>,
302
        type_: PromptType,
303
        properties: Properties,
304
        exchange: &str,
305
    ) -> Result<(), ServiceError>;
306

            
307
    fn stop_prompting(&self, callback: &ObjectPath<'_>) -> Result<(), ServiceError>;
308
}
309

            
310
#[derive(Clone)]
311
pub struct GNOMEPrompterCallback {
312
    window_id: Option<WindowIdentifierType>,
313
    private_key: Arc<Key>,
314
    public_key: Arc<Key>,
315
    exchange: OnceCell<String>,
316
    service: Service,
317
    prompt_path: OwnedObjectPath,
318
    path: OwnedObjectPath,
319
    failed_attempts: Arc<AtomicU32>,
320
    change_password_unlocked: Arc<AtomicBool>,
321
}
322

            
323
#[zbus::interface(name = "org.gnome.keyring.internal.Prompter.Callback")]
324
impl GNOMEPrompterCallback {
325
6
    pub async fn prompt_ready(
326
        &self,
327
        reply: Optional<Reply>,
328
        _properties: Properties,
329
        exchange: &str,
330
    ) -> Result<(), ServiceError> {
331
7
        let prompt_path = &self.prompt_path;
332
12
        let Some(prompt) = self.service.prompt(prompt_path).await else {
333
8
            return Err(ServiceError::NoSuchObject(format!(
334
                "Prompt '{prompt_path}' does not exist."
335
            )));
336
        };
337

            
338
12
        match *reply {
339
            // First PromptReady call
340
4
            None => {
341
6
                self.prompter_init(&prompt).await?;
342
            }
343
            // Second PromptReady call with final exchange
344
4
            Some(Reply::Yes) => {
345
18
                self.prompter_done(&prompt, exchange).await?;
346
            }
347
            // Dismissed prompt
348
4
            Some(Reply::No) => {
349
16
                self.prompter_dismissed(prompt.path().clone().into())
350
12
                    .await?;
351
            }
352
        };
353
4
        Ok(())
354
    }
355

            
356
16
    async fn prompt_done(&self) -> Result<(), ServiceError> {
357
        // This is only does check if the prompt is tracked on Service
358
4
        let path = &self.prompt_path;
359
8
        if self.service.prompt(path).await.is_some() {
360
20
            self.service
361
                .object_server()
362
4
                .remove::<Prompt, _>(path)
363
12
                .await?;
364
4
            self.service.remove_prompt(path).await;
365
        }
366
24
        self.service
367
            .object_server()
368
4
            .remove::<Self, _>(&self.path)
369
20
            .await?;
370

            
371
4
        Ok(())
372
    }
373
}
374

            
375
impl GNOMEPrompterCallback {
376
4
    pub async fn new(
377
        window_id: Option<WindowIdentifierType>,
378
        service: Service,
379
        prompt_path: OwnedObjectPath,
380
    ) -> Result<Self, oo7::crypto::Error> {
381
8
        let index = service.prompt_index();
382
8
        let private_key = Arc::new(Key::generate_private_key()?);
383
8
        let public_key = Arc::new(crate::gnome::crypto::generate_public_key(&private_key)?);
384
5
        Ok(Self {
385
5
            window_id,
386
5
            public_key,
387
6
            private_key,
388
6
            exchange: Default::default(),
389
12
            path: OwnedObjectPath::try_from(format!("/org/gnome/keyring/Prompt/p{index}")).unwrap(),
390
6
            service,
391
6
            prompt_path,
392
12
            failed_attempts: Arc::new(AtomicU32::new(0)),
393
11
            change_password_unlocked: Arc::new(AtomicBool::new(false)),
394
        })
395
    }
396

            
397
5
    pub fn path(&self) -> &ObjectPath<'_> {
398
5
        &self.path
399
    }
400

            
401
23
    async fn prompter_init(&self, prompt: &Prompt) -> Result<(), ServiceError> {
402
10
        let connection = self.service.connection();
403
10
        let exchange = secret_exchange::begin(&self.public_key);
404
7
        self.exchange.set(exchange).unwrap();
405

            
406
7
        let label = prompt.label();
407
11
        let (properties, prompt_type) = match prompt.role() {
408
4
            PromptRole::Unlock => (
409
12
                Properties::for_unlock(label, None, self.window_id.as_ref()),
410
                PromptType::Password,
411
            ),
412
4
            PromptRole::CreateCollection => (
413
8
                Properties::for_create_collection(label, self.window_id.as_ref()),
414
                PromptType::Password,
415
            ),
416
            PromptRole::ChangePassword => {
417
8
                let is_locked = if let Some(collection) = prompt.collection() {
418
8
                    collection.is_locked().await
419
                } else {
420
                    false
421
                };
422
12
                if is_locked {
423
                    (
424
8
                        Properties::for_change_password_old(label, None, self.window_id.as_ref()),
425
                        PromptType::Password,
426
                    )
427
                } else {
428
8
                    self.change_password_unlocked.store(true, Ordering::Relaxed);
429
                    (
430
4
                        Properties::for_change_password_new(label, self.window_id.as_ref()),
431
                        PromptType::Password,
432
                    )
433
                }
434
            }
435
        };
436

            
437
8
        let prompter = GNOMEPrompterProxy::new(&connection).await?;
438
8
        let path = self.path.clone();
439
8
        let exchange = self.exchange.get().unwrap().clone();
440
12
        tokio::spawn(async move {
441
21
            prompter
442
15
                .perform_prompt(&path, prompt_type, properties, &exchange)
443
25
                .await
444
        });
445
4
        Ok(())
446
    }
447

            
448
38
    async fn prompter_done(&self, prompt: &Prompt, exchange: &str) -> Result<(), ServiceError> {
449
12
        let prompter = GNOMEPrompterProxy::new(&self.service.connection()).await?;
450
6
        let aes_key = secret_exchange::handshake(&self.private_key, exchange).map_err(|err| {
451
            custom_service_error(&format!(
452
                "Failed to generate AES key for SecretExchange {err}."
453
            ))
454
        })?;
455

            
456
11
        let Some(raw_secret) = secret_exchange::retrieve(exchange, &aes_key) else {
457
            return Err(custom_service_error(
458
                "Failed to retrieve keyring secret from SecretExchange.",
459
            ));
460
        };
461

            
462
17
        let secret = if raw_secret.as_bytes().is_empty() {
463
4
            None
464
        } else {
465
6
            Some(raw_secret)
466
        };
467

            
468
        // Handle each role differently based on what validation/preparation is
469
        // needed
470
12
        match prompt.role() {
471
            PromptRole::Unlock => {
472
16
                if prompt.on_unlock_collection(secret).await? {
473
4
                    let path = self.path.clone();
474
12
                    tokio::spawn(async move { prompter.stop_prompting(&path).await });
475
                } else {
476
8
                    let attempts = self.failed_attempts.fetch_add(1, Ordering::Relaxed) + 1;
477
4
                    if attempts >= MAX_UNLOCK_ATTEMPTS {
478
8
                        tracing::warn!(
479
                            "Maximum unlock attempts ({MAX_UNLOCK_ATTEMPTS}) reached, \
480
                             dismissing prompt."
481
                        );
482
20
                        self.prompter_dismissed(prompt.path().clone().into())
483
12
                            .await?;
484
4
                        let path = self.path.clone();
485
12
                        tokio::spawn(async move { prompter.stop_prompting(&path).await });
486
                    } else {
487
                        let properties = Properties::for_unlock(
488
4
                            prompt.label(),
489
                            Some("The unlock password was incorrect"),
490
4
                            self.window_id.as_ref(),
491
                        );
492
4
                        let server_exchange = self
493
                            .exchange
494
                            .get()
495
                            .expect("Exchange cannot be empty at this stage")
496
                            .clone();
497
4
                        let path = self.path.clone();
498

            
499
12
                        tokio::spawn(async move {
500
16
                            prompter
501
4
                                .perform_prompt(
502
4
                                    &path,
503
                                    PromptType::Password,
504
4
                                    properties,
505
4
                                    &server_exchange,
506
                                )
507
20
                                .await
508
                        });
509
                    }
510
                }
511
            }
512
            PromptRole::CreateCollection => {
513
17
                prompt.on_create_collection(secret).await?;
514

            
515
5
                let path = self.path.clone();
516
14
                tokio::spawn(async move { prompter.stop_prompting(&path).await });
517
            }
518
            PromptRole::ChangePassword => {
519
12
                if self.change_password_unlocked.load(Ordering::Relaxed) {
520
17
                    prompt.on_change_password(secret).await?;
521

            
522
4
                    let path = self.path.clone();
523
12
                    tokio::spawn(async move { prompter.stop_prompting(&path).await });
524
                } else {
525
8
                    let collection = prompt
526
                        .collection()
527
                        .expect("ChangePassword requires a collection");
528
12
                    let properties = match self.service.unlock_collection(collection, secret).await
529
                    {
530
                        Ok(()) => {
531
8
                            self.change_password_unlocked.store(true, Ordering::Relaxed);
532
                            Properties::for_change_password_new(
533
4
                                prompt.label(),
534
4
                                self.window_id.as_ref(),
535
                            )
536
                        }
537
                        Err(_) => Properties::for_change_password_old(
538
4
                            prompt.label(),
539
4
                            Some(&gettext("The original password was incorrect")),
540
4
                            self.window_id.as_ref(),
541
                        ),
542
                    };
543
4
                    let server_exchange = self
544
                        .exchange
545
                        .get()
546
                        .expect("Exchange cannot be empty at this stage")
547
                        .clone();
548
4
                    let path = self.path.clone();
549
12
                    tokio::spawn(async move {
550
16
                        prompter
551
4
                            .perform_prompt(
552
4
                                &path,
553
                                PromptType::Password,
554
4
                                properties,
555
4
                                &server_exchange,
556
                            )
557
20
                            .await
558
                    });
559
                }
560
            }
561
        }
562
4
        Ok(())
563
    }
564

            
565
16
    async fn prompter_dismissed(&self, prompt_path: OwnedObjectPath) -> Result<(), ServiceError> {
566
8
        let path = self.path.clone();
567
8
        let prompter = GNOMEPrompterProxy::new(&self.service.connection()).await?;
568

            
569
12
        tokio::spawn(async move { prompter.stop_prompting(&path).await });
570
8
        let signal_emitter = self.service.signal_emitter(prompt_path)?;
571
8
        let result = wire::Variant::new::<Vec<OwnedObjectPath>>(vec![])
572
            .try_into_owned()
573
            .unwrap();
574

            
575
12
        tokio::spawn(async move { Prompt::completed(&signal_emitter, true, result).await });
576
4
        Ok(())
577
    }
578
}
579

            
580
#[cfg(test)]
581
mod tests {
582
    use std::collections::HashMap;
583

            
584
    use wire::{serialized::Context, to_bytes};
585

            
586
    use super::*;
587

            
588
    #[test]
589
    fn properties_serialization_roundtrip() {
590
        let props = Properties {
591
            title: Some("Test Title".to_string()),
592
            message: Some("Test Message".to_string()),
593
            ..Default::default()
594
        };
595

            
596
        // Serialize to bytes
597
        let ctxt = Context::new(wire::LE, 0);
598
        let encoded = to_bytes(ctxt, &props).expect("Failed to serialize");
599

            
600
        // Deserialize back to verify roundtrip works
601
        let decoded: Properties = encoded.deserialize().unwrap().0;
602

            
603
        assert_eq!(decoded.title, Some("Test Title".to_string()));
604
        assert_eq!(decoded.message, Some("Test Message".to_string()));
605
    }
606

            
607
    #[test]
608
    fn deserialize_properties() {
609
        let mut map: HashMap<String, Variant> = HashMap::new();
610

            
611
        // Double-wrap: Variant<Variant<String>>
612
        map.insert(
613
            "title".to_string(),
614
            Variant::new(Variant::new("Unlock Keyring")),
615
        );
616

            
617
        map.insert(
618
            "message".to_string(),
619
            Variant::new(Variant::new("Authentication required")),
620
        );
621

            
622
        // Serialize the HashMap
623
        let ctxt = Context::new(wire::LE, 0);
624
        let encoded = to_bytes(ctxt, &map).expect("Failed to serialize test data");
625

            
626
        // Deserialize as Properties
627
        let props: Properties = encoded.deserialize().unwrap().0;
628

            
629
        assert_eq!(props.title, Some("Unlock Keyring".to_string()));
630
        assert_eq!(props.message, Some("Authentication required".to_string()));
631

            
632
        let mut map: HashMap<String, Variant> = HashMap::new();
633

            
634
        // Single-wrap: Variant<String> (the correct format)
635
        map.insert("title".to_string(), Variant::new("Unlock Keyring"));
636
        map.insert(
637
            "message".to_string(),
638
            Variant::new("Authentication required"),
639
        );
640

            
641
        // Serialize the HashMap
642
        let ctxt = Context::new(wire::LE, 0);
643
        let encoded = to_bytes(ctxt, &map).expect("Failed to serialize test data");
644

            
645
        // Deserialize as Properties - should also work
646
        let props: Properties = encoded.deserialize().unwrap().0;
647

            
648
        assert_eq!(props.title, Some("Unlock Keyring".to_string()));
649
        assert_eq!(props.message, Some("Authentication required".to_string()));
650

            
651
        let props = Properties {
652
            title: None,
653
            message: Some("Test".to_string()),
654
            ..Default::default()
655
        };
656

            
657
        let ctxt = Context::new(wire::LE, 0);
658
        let encoded = to_bytes(ctxt, &props).expect("Failed to serialize");
659
        let decoded: Properties = encoded.deserialize().unwrap().0;
660

            
661
        assert_eq!(decoded.title, None);
662
        assert_eq!(decoded.message, Some("Test".to_string()));
663

            
664
        let props = Properties {
665
            password_new: Some(true),
666
            password_strength: Some(42),
667
            choice_chosen: Some(false),
668
            ..Default::default()
669
        };
670

            
671
        let ctxt = Context::new(wire::LE, 0);
672
        let encoded = to_bytes(ctxt, &props).expect("Failed to serialize");
673
        let decoded: Properties = encoded.deserialize().unwrap().0;
674

            
675
        assert_eq!(decoded.password_new, Some(true));
676
        assert_eq!(decoded.password_strength, Some(42));
677
        assert_eq!(decoded.choice_chosen, Some(false));
678
    }
679
}