1
use std::{collections::HashMap, sync::Arc};
2

            
3
use base64::Engine;
4
use oo7::{Secret, crypto};
5
use zbus::wire::{ObjectPath, Optional, Variant};
6

            
7
use super::{
8
    prompter::{PromptType, Properties, Reply},
9
    secret_exchange,
10
};
11

            
12
/// Mock implementation of org.gnome.keyring.internal.Prompter
13
///
14
/// This simulates the GNOME System Prompter for testing without requiring
15
/// the actual GNOME keyring prompter service to be running.
16
#[derive(Clone)]
17
pub(crate) struct MockPrompterServiceGNOME {
18
    /// The password to use for unlock prompts (simulates user input)
19
    unlock_password: Arc<tokio::sync::Mutex<Option<Secret>>>,
20
    /// Whether to accept (true) or dismiss (false) prompts
21
    should_accept: Arc<tokio::sync::Mutex<bool>>,
22
    /// Queue of passwords to use for for testing retry logic
23
    password_queue: Arc<tokio::sync::Mutex<Vec<Secret>>>,
24
}
25

            
26
#[allow(unused)]
27
impl MockPrompterServiceGNOME {
28
10
    pub fn new() -> Self {
29
        Self {
30
6
            unlock_password: Arc::new(tokio::sync::Mutex::new(Some(Secret::from(
31
                "test-password-long-enough",
32
            )))),
33
16
            should_accept: Arc::new(tokio::sync::Mutex::new(true)),
34
14
            password_queue: Arc::new(tokio::sync::Mutex::new(Vec::new())),
35
        }
36
    }
37

            
38
    /// Set whether prompts should be accepted or dismissed
39
16
    pub async fn set_accept(&self, accept: bool) {
40
8
        *self.should_accept.lock().await = accept;
41
    }
42

            
43
16
    pub async fn set_password_queue(&self, passwords: Vec<Secret>) {
44
4
        *self.password_queue.lock().await = passwords;
45
    }
46
}
47

            
48
#[allow(unused)]
49
#[zbus::interface(name = "org.gnome.keyring.internal.Prompter")]
50
impl MockPrompterServiceGNOME {
51
6
    async fn begin_prompting(
52
        &self,
53
        callback: ObjectPath<'_>,
54
        #[zbus(connection)] connection: &zbus::Connection,
55
    ) -> zbus::fdo::Result<()> {
56
14
        tracing::debug!("MockPrompter: begin_prompting called for {}", callback);
57
10
        let callback_path = callback.to_owned();
58
10
        let connection = connection.clone();
59

            
60
        // Spawn a task to send the initial prompt_ready call
61
18
        tokio::spawn(async move {
62
12
            tracing::debug!("MockPrompter: spawned task starting");
63
            // Small delay to ensure callback is fully registered
64
13
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
65

            
66
            // Call PromptReady directly without building a proxy (avoids
67
            // introspection issues in p2p)
68
13
            tracing::debug!(
69
                "MockPrompter: calling PromptReady with None on {}",
70
                callback_path
71
            );
72
7
            let properties: HashMap<String, Variant> = HashMap::new();
73
11
            let empty_exchange = "";
74

            
75
21
            connection
76
7
                .call_method(
77
                    None::<()>, // No destination in p2p
78
                    &callback_path,
79
                    Some("org.gnome.keyring.internal.Prompter.Callback"),
80
                    "PromptReady",
81
14
                    &(Optional::<Reply>::from(None), properties, empty_exchange),
82
                )
83
18
                .await?;
84

            
85
8
            tracing::debug!("MockPrompter: PromptReady(None) completed");
86
4
            Ok::<_, zbus::Error>(())
87
        });
88

            
89
5
        Ok(())
90
    }
91

            
92
4
    async fn perform_prompt(
93
        &self,
94
        callback: ObjectPath<'_>,
95
        type_: PromptType,
96
        _properties: Properties,
97
        exchange: &str,
98
        #[zbus(connection)] connection: &zbus::Connection,
99
    ) -> zbus::fdo::Result<()> {
100
11
        tracing::debug!(
101
            "MockPrompter: perform_prompt called for {}, type={:?}",
102
            callback,
103
            type_
104
        );
105
        // This is called by GNOMEPrompterCallback.prompter_init() with the
106
        // server's exchange
107
8
        let callback_path = callback.to_owned();
108
9
        let unlock_password = self.unlock_password.clone();
109
9
        let should_accept = self.should_accept.clone();
110
9
        let password_queue = self.password_queue.clone();
111
10
        let exchange = exchange.to_owned();
112
10
        let connection = connection.clone();
113

            
114
        // Spawn a task to simulate user interaction and send final response
115
23
        tokio::spawn(async move {
116
14
            tracing::debug!("MockPrompter: perform_prompt task starting");
117
            // Small delay to simulate user interaction
118
17
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
119

            
120
7
            let accept = *should_accept.lock().await;
121
7
            let properties: HashMap<String, Variant> = HashMap::new();
122

            
123
7
            if !accept {
124
10
                tracing::debug!("MockPrompter: dismissing prompt");
125
                // Dismiss the prompt
126
16
                connection
127
4
                    .call_method(
128
                        None::<()>, // No destination in p2p
129
                        &callback_path,
130
                        Some("org.gnome.keyring.internal.Prompter.Callback"),
131
                        "PromptReady",
132
4
                        &(Reply::No, properties, ""),
133
                    )
134
16
                    .await?;
135
8
                tracing::debug!("MockPrompter: PromptReady(no) completed");
136

            
137
4
                return Ok(());
138
14
            } else if type_ == PromptType::Password {
139
19
                tracing::debug!("MockPrompter: performing unlock (password prompt)");
140
                // Unlock prompt - perform secret exchange
141

            
142
14
                let mut queue = password_queue.lock().await;
143
22
                let password = if !queue.is_empty() {
144
8
                    let pwd = queue.remove(0);
145
10
                    tracing::debug!(
146
                        "MockPrompter: using password from queue (length: {}, queue remaining: {})",
147
                        pwd.as_str().unwrap_or("<binary>"),
148
                        queue.len()
149
                    );
150
4
                    pwd
151
                } else {
152
8
                    let pwd = unlock_password.lock().await.clone().unwrap();
153
8
                    tracing::debug!(
154
                        "MockPrompter: using default password (length: {})",
155
                        pwd.as_str().unwrap_or("<binary>")
156
                    );
157
4
                    pwd
158
                };
159
4
                drop(queue);
160

            
161
                // Generate our own key pair
162
6
                let private_key = oo7::Key::generate_private_key().unwrap();
163
14
                let public_key = super::crypto::generate_public_key(&private_key).unwrap();
164

            
165
                // Handshake with server's exchange to get AES key
166
14
                let aes_key = secret_exchange::handshake(&private_key, &exchange).unwrap();
167

            
168
                // Encrypt the password
169
14
                let iv = crypto::generate_iv().unwrap();
170
15
                let encrypted = crypto::encrypt(password.as_bytes(), &aes_key, &iv).unwrap();
171

            
172
                // Create final exchange with encrypted secret
173
8
                let final_exchange = format!(
174
                    "[sx-aes-1]\npublic={}\nsecret={}\niv={}",
175
16
                    base64::prelude::BASE64_STANDARD.encode(public_key.as_ref()),
176
8
                    base64::prelude::BASE64_STANDARD.encode(&encrypted),
177
8
                    base64::prelude::BASE64_STANDARD.encode(&iv)
178
                );
179

            
180
14
                tracing::debug!("MockPrompter: calling PromptReady with yes");
181
24
                connection
182
6
                    .call_method(
183
                        None::<()>, // No destination in p2p
184
                        &callback_path,
185
                        Some("org.gnome.keyring.internal.Prompter.Callback"),
186
                        "PromptReady",
187
6
                        &(Reply::Yes, properties, final_exchange.as_str()),
188
                    )
189
28
                    .await?;
190
8
                tracing::debug!("MockPrompter: PromptReady(yes) with secret exchange completed");
191
            } else {
192
                tracing::debug!("MockPrompter: accepting confirm prompt");
193
                // Lock/confirm prompt - just accept
194
                connection
195
                    .call_method(
196
                        None::<()>, // No destination in p2p
197
                        &callback_path,
198
                        Some("org.gnome.keyring.internal.Prompter.Callback"),
199
                        "PromptReady",
200
                        &(Reply::Yes, properties, ""),
201
                    )
202
                    .await?;
203
                tracing::debug!("MockPrompter: PromptReady(yes) completed");
204
            }
205

            
206
4
            Ok::<_, zbus::Error>(())
207
        });
208

            
209
5
        Ok(())
210
    }
211

            
212
4
    async fn stop_prompting(
213
        &self,
214
        callback: ObjectPath<'_>,
215
        #[zbus(connection)] connection: &zbus::Connection,
216
    ) -> zbus::fdo::Result<()> {
217
10
        tracing::debug!("MockPrompter: stop_prompting called for {}", callback);
218
8
        let callback_path = callback.to_owned();
219
8
        let connection = connection.clone();
220

            
221
12
        tokio::spawn(async move {
222
10
            tracing::debug!("MockPrompter: calling PromptDone for {}", callback_path);
223
12
            let result = connection
224
4
                .call_method(
225
                    None::<()>,
226
                    &callback_path,
227
                    Some("org.gnome.keyring.internal.Prompter.Callback"),
228
                    "PromptDone",
229
                    &(),
230
                )
231
16
                .await;
232

            
233
8
            if let Err(err) = result {
234
10
                tracing::debug!("MockPrompter: PromptDone failed: {}", err);
235
            } else {
236
10
                tracing::debug!("MockPrompter: PromptDone completed for {}", callback_path);
237
            }
238
        });
239

            
240
4
        Ok(())
241
    }
242
}