1
// SPDX-License-Identifier: MIT
2
// SPDX-FileCopyrightText: 2025 Harald Sitter <sitter@kde.org>
3

            
4
use std::{
5
    os::fd::AsFd,
6
    sync::{
7
        Arc,
8
        atomic::{AtomicU32, Ordering},
9
    },
10
};
11

            
12
use ashpd::WindowIdentifierType;
13
use gettextrs::gettext;
14
use oo7::{Secret, dbus::ServiceError};
15
use serde::Serialize;
16
use tokio::io::AsyncReadExt;
17
use zbus::{
18
    object_server::SignalEmitter,
19
    wire::{self, ObjectPath, OwnedFd, OwnedObjectPath, Type},
20
};
21

            
22
use crate::{
23
    prompt::{MAX_UNLOCK_ATTEMPTS, Prompt, PromptRole},
24
    service::Service,
25
};
26

            
27
#[repr(i32)]
28
#[derive(Type, Serialize)]
29
pub enum CallbackAction {
30
    Dismiss = 0,
31
    Keep = 1,
32
}
33

            
34
#[must_use]
35
pub async fn in_plasma_environment(connection: &zbus::Connection) -> bool {
36
    static IS_PLASMA: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
37
    if let Some(cached_value) = IS_PLASMA.get() {
38
        return *cached_value;
39
    }
40

            
41
    let is_plasma = async {
42
        if !std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|v| v.to_lowercase() == "kde") {
43
            return false;
44
        }
45

            
46
        let proxy = match zbus::fdo::DBusProxy::new(connection).await {
47
            Ok(proxy) => proxy,
48
            Err(_) => return false,
49
        };
50
        let activatable_names = match proxy.list_activatable_names().await {
51
            Ok(names) => names,
52
            Err(_) => return false,
53
        };
54
        activatable_names
55
            .iter()
56
            .any(|name| name.as_str() == "org.kde.secretprompter")
57
    }
58
    .await;
59

            
60
    *IS_PLASMA.get_or_init(|| is_plasma)
61
}
62

            
63
#[zbus::proxy(
64
    default_service = "org.kde.secretprompter",
65
    interface = "org.kde.secretprompter",
66
    default_path = "/SecretPrompter"
67
)]
68
pub trait PlasmaPrompter {
69
    fn unlock_collection_prompt(
70
        &self,
71
        request: &ObjectPath<'_>,
72
        window_id: &str,
73
        activation_token: &str,
74
        collection_name: &str,
75
    ) -> Result<(), ServiceError>;
76
    fn create_collection_prompt(
77
        &self,
78
        request: &ObjectPath<'_>,
79
        window_id: &str,
80
        activation_token: &str,
81
        collection_name: &str,
82
    ) -> Result<(), ServiceError>;
83
}
84

            
85
#[derive(Clone)]
86
pub struct PlasmaPrompterCallback {
87
    service: Service,
88
    prompt_path: OwnedObjectPath,
89
    path: OwnedObjectPath,
90
    failed_attempts: Arc<AtomicU32>,
91
}
92

            
93
#[zbus::interface(name = "org.kde.secretprompter.request")]
94
impl PlasmaPrompterCallback {
95
28
    pub async fn accepted(&self, result_fd: OwnedFd) -> Result<CallbackAction, ServiceError> {
96
4
        let prompt_path = &self.prompt_path;
97
8
        let Some(prompt) = self.service.prompt(prompt_path).await else {
98
            return Err(ServiceError::NoSuchObject(format!(
99
                "Prompt '{prompt_path}' does not exist."
100
            )));
101
        };
102

            
103
8
        tracing::debug!("User accepted the prompt.");
104

            
105
        let secret = {
106
8
            let borrowed_fd = result_fd.as_fd();
107
            let std_stream = std::os::unix::net::UnixStream::from(
108
4
                borrowed_fd
109
4
                    .try_clone_to_owned()
110
4
                    .expect("Failed to clone fd"),
111
            );
112
4
            let mut stream = tokio::net::UnixStream::from_std(std_stream)
113
                .expect("Failed to create Tokio UnixStream");
114
4
            let mut buffer = String::new();
115
12
            stream
116
4
                .read_to_string(&mut buffer)
117
16
                .await
118
                .expect("error reading secret");
119
4
            tracing::debug!("Read secret from fd, length {}", buffer.len());
120
8
            if buffer.is_empty() {
121
                None
122
            } else {
123
8
                Some(oo7::Secret::from(buffer))
124
            }
125
        };
126

            
127
8
        self.on_reply(&prompt, secret).await
128
    }
129

            
130
16
    pub async fn rejected(&self) -> Result<CallbackAction, ServiceError> {
131
8
        tracing::debug!("User rejected the prompt.");
132
8
        self.prompter_dismissed(self.prompt_path.clone()).await?;
133
4
        Ok(CallbackAction::Dismiss) // simply dismiss without further action
134
    }
135

            
136
16
    pub async fn dismissed(&self) -> Result<(), ServiceError> {
137
        // This is only does check if the prompt is tracked on Service
138
4
        let path = &self.prompt_path;
139
8
        if let Some(_prompt) = self.service.prompt(path).await {
140
20
            self.service
141
                .object_server()
142
4
                .remove::<Prompt, _>(path)
143
12
                .await?;
144
4
            self.service.remove_prompt(path).await;
145
        }
146
20
        self.service
147
            .object_server()
148
4
            .remove::<Self, _>(&self.path)
149
12
            .await?;
150

            
151
4
        Ok(())
152
    }
153

            
154
    #[zbus(signal)]
155
4
    pub async fn retry(signal_emitter: &SignalEmitter<'_>, reason: &str) -> zbus::Result<()>;
156

            
157
    #[zbus(signal)]
158
    pub async fn dismiss(signal_emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
159
}
160

            
161
impl PlasmaPrompterCallback {
162
16
    pub async fn new(service: Service, prompt_path: OwnedObjectPath) -> Self {
163
8
        let index = service.prompt_index();
164
        Self {
165
4
            path: OwnedObjectPath::try_from(format!("/org/plasma/keyring/Prompt/p{index}"))
166
                .unwrap(),
167
            service,
168
            prompt_path,
169
8
            failed_attempts: Arc::new(AtomicU32::new(0)),
170
        }
171
    }
172

            
173
4
    pub fn path(&self) -> &ObjectPath<'_> {
174
4
        &self.path
175
    }
176

            
177
4
    pub async fn start(
178
        &self,
179
        role: &PromptRole,
180
        window_id: Option<WindowIdentifierType>,
181
        collection_name: &str,
182
    ) -> Result<(), ServiceError> {
183
8
        let path = self.path.clone();
184
8
        let prompter = PlasmaPrompterProxy::new(&self.service.connection()).await?;
185
4
        let window_id = match window_id {
186
            Some(id) => id.to_string(),
187
8
            None => String::new(),
188
        };
189
4
        let collection_name = collection_name.to_string();
190

            
191
4
        match role {
192
            PromptRole::Unlock => {
193
16
                tokio::spawn(async move {
194
12
                    prompter
195
8
                        .unlock_collection_prompt(&path, &window_id, "", collection_name.as_str())
196
16
                        .await
197
                });
198
            }
199
            PromptRole::CreateCollection => {
200
16
                tokio::spawn(async move {
201
12
                    prompter
202
8
                        .create_collection_prompt(&path, &window_id, "", collection_name.as_str())
203
16
                        .await
204
                });
205
            }
206
            PromptRole::ChangePassword => {
207
                tokio::spawn(async move {
208
                    prompter
209
                        .unlock_collection_prompt(&path, &window_id, "", collection_name.as_str())
210
                        .await
211
                });
212
            }
213
        }
214

            
215
4
        Ok(())
216
    }
217

            
218
4
    async fn on_reply(
219
        &self,
220
        prompt: &Prompt,
221
        secret: Option<Secret>,
222
    ) -> Result<CallbackAction, ServiceError> {
223
        // Handle each role differently based on what validation/preparation is
224
        // needed
225
8
        match prompt.role() {
226
            PromptRole::Unlock => {
227
16
                if prompt.on_unlock_collection(secret).await? {
228
4
                    Ok(CallbackAction::Dismiss)
229
                } else {
230
8
                    let attempts = self.failed_attempts.fetch_add(1, Ordering::Relaxed) + 1;
231
8
                    if attempts >= MAX_UNLOCK_ATTEMPTS {
232
8
                        tracing::warn!(
233
                            "Maximum unlock attempts ({MAX_UNLOCK_ATTEMPTS}) reached, \
234
                             dismissing prompt."
235
                        );
236
8
                        self.prompter_dismissed(self.prompt_path.clone()).await?;
237
4
                        Ok(CallbackAction::Dismiss)
238
                    } else {
239
8
                        tracing::debug!("Unlock failed, sending retry signal.");
240
                        let emitter = SignalEmitter::from_parts(
241
12
                            self.service.connection().clone(),
242
8
                            self.path().clone(),
243
                        );
244
                        PlasmaPrompterCallback::retry(
245
4
                            &emitter,
246
4
                            &gettext("The unlock password was incorrect"),
247
                        )
248
16
                        .await?;
249

            
250
4
                        Ok(CallbackAction::Keep)
251
                    }
252
                }
253
            }
254
            PromptRole::CreateCollection => {
255
12
                prompt.on_create_collection(secret).await?;
256
4
                Ok(CallbackAction::Dismiss)
257
            }
258
            PromptRole::ChangePassword => {
259
                prompt.on_change_password(secret).await?;
260
                Ok(CallbackAction::Dismiss)
261
            }
262
        }
263
    }
264

            
265
16
    async fn prompter_dismissed(&self, prompt_path: OwnedObjectPath) -> Result<(), ServiceError> {
266
8
        let signal_emitter = self.service.signal_emitter(prompt_path)?;
267
8
        let result = wire::Variant::new::<Vec<OwnedObjectPath>>(vec![])
268
            .try_into_owned()
269
            .unwrap();
270

            
271
12
        tokio::spawn(async move { Prompt::completed(&signal_emitter, true, result).await });
272
4
        Ok(())
273
    }
274
}