1
use std::{io::Write, os::unix::net::UnixStream, sync::Arc};
2

            
3
use oo7::Secret;
4
use tokio_stream::StreamExt;
5
use zbus::wire::{Fd, ObjectPath};
6

            
7
/// Mock implementation of org.kde.secretprompter
8
///
9
/// This simulates the Plasma System Prompter for testing without requiring
10
/// the actual service to be running.
11
#[derive(Clone)]
12
pub(crate) struct MockPrompterServicePlasma {
13
    /// The password to use for unlock prompts (simulates user input)
14
    unlock_password: Arc<tokio::sync::Mutex<Option<Secret>>>,
15
    /// Whether to accept (true) or dismiss (false) prompts
16
    should_accept: Arc<tokio::sync::Mutex<bool>>,
17
    /// Queue of passwords to use for for testing retry logic
18
    password_queue: Arc<tokio::sync::Mutex<Vec<Secret>>>,
19
}
20

            
21
#[allow(unused)]
22
impl MockPrompterServicePlasma {
23
8
    pub fn new() -> Self {
24
        Self {
25
6
            unlock_password: Arc::new(tokio::sync::Mutex::new(Some(Secret::from(
26
                "test-password-long-enough",
27
            )))),
28
14
            should_accept: Arc::new(tokio::sync::Mutex::new(true)),
29
14
            password_queue: Arc::new(tokio::sync::Mutex::new(Vec::new())),
30
        }
31
    }
32

            
33
    /// Set whether prompts should be accepted or dismissed
34
16
    pub async fn set_accept(&self, accept: bool) {
35
8
        *self.should_accept.lock().await = accept;
36
    }
37

            
38
16
    pub async fn set_password_queue(&self, passwords: Vec<Secret>) {
39
4
        *self.password_queue.lock().await = passwords;
40
    }
41

            
42
4
    pub async fn send_secret(
43
        connection: &zbus::Connection,
44
        callback_path: &ObjectPath<'_>,
45
        secret: &Secret,
46
    ) -> zbus::fdo::Result<()> {
47
8
        let callback_path = callback_path.to_owned();
48
8
        let connection = connection.clone();
49
4
        let secret = secret.clone();
50

            
51
        // Accepted case
52
12
        tokio::spawn(async move {
53
12
            tracing::debug!(
54
                "MockPrompterServicePlasma: calling Accepted on {}",
55
                callback_path
56
            );
57

            
58
4
            let (read_end, mut write_end) =
59
8
                UnixStream::pair().expect("Failed to create socketpair");
60
8
            read_end.set_nonblocking(true).unwrap();
61
4
            write_end.set_nonblocking(true).unwrap();
62
4
            write_end.write_all(secret.as_bytes()).unwrap();
63
4
            drop(write_end); // Close write end to signal EOF
64

            
65
16
            connection
66
4
                .call_method(
67
                    None::<()>, // No destination in p2p
68
4
                    &callback_path,
69
                    Some("org.kde.secretprompter.request"),
70
                    "Accepted",
71
4
                    &(Fd::Owned(read_end.into())),
72
                )
73
16
                .await?;
74

            
75
8
            tracing::debug!(
76
                "MockPrompterServicePlasma: Accepted completed for {}",
77
                callback_path
78
            );
79
4
            Ok::<_, zbus::Error>(())
80
        });
81

            
82
4
        Ok(())
83
    }
84
}
85

            
86
#[allow(unused)]
87
#[zbus::interface(name = "org.kde.secretprompter")]
88
impl MockPrompterServicePlasma {
89
4
    async fn unlock_collection_prompt(
90
        &self,
91
        request: ObjectPath<'_>,
92
        _window_id: &str,
93
        _activation_token: &str,
94
        _collection_name: &str,
95
        #[zbus(connection)] connection: &zbus::Connection,
96
    ) -> zbus::fdo::Result<()> {
97
10
        tracing::debug!(
98
            "MockPrompterServicePlasma: unlock_collection_prompt called for {}",
99
            request
100
        );
101

            
102
8
        let callback_path = request.to_owned();
103
8
        let connection = connection.clone();
104

            
105
        // Reject case
106
8
        if !*self.should_accept.lock().await {
107
12
            tokio::spawn(async move {
108
10
                tracing::debug!(
109
                    "MockPrompterServicePlasma: dismissing prompt for {}",
110
                    callback_path
111
                );
112

            
113
20
                connection
114
4
                    .call_method(
115
                        None::<()>, // No destination in p2p
116
                        &callback_path,
117
                        Some("org.kde.secretprompter.request"),
118
                        "Rejected",
119
                        &(),
120
                    )
121
16
                    .await
122
8
                    .unwrap();
123

            
124
8
                tracing::debug!(
125
                    "MockPrompterServicePlasma: Dismissed completed for {}",
126
                    callback_path
127
                );
128
            });
129
4
            return Ok(());
130
        }
131

            
132
8
        let mut queue = self.password_queue.lock().await.clone();
133
4
        self.password_queue.lock().await.clear();
134
4
        if !queue.is_empty() {
135
24
            tokio::spawn(async move {
136
24
                let proxy: zbus::proxy::Proxy<'_> = zbus::proxy::Builder::new(&connection)
137
4
                    .destination("org.kde.client") // apparently unused but still required for p2p
138
8
                    .path(callback_path.clone())
139
4
                    .interface("org.kde.secretprompter.request")
140
4
                    .build()
141
12
                    .await
142
4
                    .unwrap();
143
12
                let mut signal_stream = proxy.receive_signal("Retry").await.unwrap();
144

            
145
                loop {
146
4
                    let secret = queue.remove(0);
147
16
                    MockPrompterServicePlasma::send_secret(&connection, &callback_path, &secret)
148
16
                        .await
149
4
                        .unwrap();
150

            
151
4
                    if queue.is_empty() {
152
                        break;
153
                    }
154

            
155
                    // Wait for Retry signal before sending next secret from the
156
                    // queue
157
20
                    signal_stream.next().await;
158
                }
159
            });
160
        } else {
161
8
            let pwd = self.unlock_password.lock().await.clone().unwrap();
162
1
            tracing::debug!(
163
                "MockPrompterServicePlasma: using default password (length: {})",
164
                pwd.as_str().unwrap_or("<binary>")
165
            );
166
8
            MockPrompterServicePlasma::send_secret(&connection, &callback_path, &pwd).await?;
167
        };
168

            
169
4
        Ok(())
170
    }
171

            
172
4
    async fn create_collection_prompt(
173
        &self,
174
        request: ObjectPath<'_>,
175
        window_id: &str,
176
        activation_token: &str,
177
        collection_name: &str,
178
        #[zbus(connection)] connection: &zbus::Connection,
179
    ) -> zbus::fdo::Result<()> {
180
10
        tracing::debug!(
181
            "MockPrompterServicePlasma: create_collection_prompt called for {}",
182
            request
183
        );
184
        // Behavior is identical for both prompts. Visualization would be
185
        // different.
186
16
        self.unlock_collection_prompt(
187
4
            request,
188
            window_id,
189
            activation_token,
190
            collection_name,
191
            connection,
192
        )
193
12
        .await?;
194
4
        Ok(())
195
    }
196
}