1
use std::path::PathBuf;
2

            
3
use oo7::{
4
    Secret,
5
    file::{Keyring, LockedKeyring},
6
};
7

            
8
use crate::{
9
    error::Error,
10
    migration::{self, PendingMigration},
11
};
12

            
13
const LOGIN_ALIAS: &str = "login";
14

            
15
pub(crate) struct LoadedKeyring {
16
    pub name: String,
17
    pub label: String,
18
    pub alias: String,
19
    pub keyring: Keyring,
20
    pub pending_migration: Option<PendingMigration>,
21
}
22

            
23
4
fn capitalize(name: &str) -> String {
24
4
    let mut chars = name.chars();
25
4
    match chars.next() {
26
        None => String::new(),
27
4
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
28
    }
29
}
30

            
31
/// Discover existing keyrings in the data directory
32
4
pub(crate) async fn discover_keyrings(
33
    data_dir: &PathBuf,
34
    secret: Option<Secret>,
35
) -> Result<Vec<LoadedKeyring>, Error> {
36
4
    let mut discovered = Vec::new();
37

            
38
8
    let keyrings_dir = data_dir.join("keyrings");
39

            
40
    // Scan for v1 keyrings first
41
8
    let v1_dir = keyrings_dir.join("v1");
42
8
    if v1_dir.exists() {
43
4
        tracing::debug!("Scanning for v1 keyrings in {}", v1_dir.display());
44
16
        if let Ok(mut entries) = tokio::fs::read_dir(&v1_dir).await {
45
16
            while let Ok(Some(entry)) = entries.next_entry().await {
46
5
                let path = entry.path();
47

            
48
                // Skip directories and non-.keyring files
49
10
                if path.is_dir() || path.extension() != Some(std::ffi::OsStr::new("keyring")) {
50
                    continue;
51
                }
52

            
53
15
                if let Some(name) = path.file_stem().and_then(|s| s.to_str()) {
54
10
                    tracing::debug!("Found v1 keyring: {name}");
55

            
56
                    // Try to load the keyring
57
24
                    match load_keyring(data_dir, &path, name, secret.as_ref()).await {
58
4
                        Ok(loaded) => discovered.push(loaded),
59
                        Err(e) => tracing::warn!("Failed to load keyring {:?}: {}", path, e),
60
                    }
61
                }
62
            }
63
        }
64
    }
65

            
66
    // Scan for v0 keyrings
67
8
    if keyrings_dir.exists() {
68
4
        tracing::debug!("Scanning for v0 keyrings in {}", keyrings_dir.display());
69
16
        if let Ok(mut entries) = tokio::fs::read_dir(&keyrings_dir).await {
70
16
            while let Ok(Some(entry)) = entries.next_entry().await {
71
4
                let path = entry.path();
72

            
73
                // Skip directories and non-.keyring files
74
8
                if path.is_dir() || path.extension() != Some(std::ffi::OsStr::new("keyring")) {
75
                    continue;
76
                }
77

            
78
4
                if migration::stamp_path(&path).exists() {
79
                    continue;
80
                }
81

            
82
12
                if let Some(name) = path.file_stem().and_then(|s| s.to_str()) {
83
8
                    tracing::debug!("Found v0 keyring: {name}");
84

            
85
                    // Try to load the keyring
86
20
                    match load_keyring(data_dir, &path, name, secret.as_ref()).await {
87
4
                        Ok(loaded) => discovered.push(loaded),
88
4
                        Err(e) => tracing::warn!("Failed to load keyring {:?}: {}", path, e),
89
                    }
90
                }
91
            }
92
        }
93
    }
94

            
95
    // Discover KWallet keyrings for migration
96
    #[cfg(feature = "kwallet_migration")]
97
    discover_kwallet_keyrings(data_dir, secret.as_ref(), &mut discovered).await;
98

            
99
8
    let pending_count = discovered
100
        .iter()
101
12
        .filter(|d| d.pending_migration.is_some())
102
        .count();
103

            
104
8
    if discovered.is_empty() && pending_count == 0 {
105
8
        tracing::info!("No keyrings discovered in data directory");
106
    } else {
107
4
        tracing::info!(
108
            "Discovered {} keyring(s), {pending_count} pending migration(s)",
109
            discovered.len(),
110
        );
111
    }
112

            
113
4
    Ok(discovered)
114
}
115

            
116
/// Load a single keyring from a file path
117
4
async fn load_keyring(
118
    data_dir: &PathBuf,
119
    path: &std::path::Path,
120
    name: &str,
121
    secret: Option<&Secret>,
122
) -> Result<LoadedKeyring, Error> {
123
13
    let alias = if name.eq_ignore_ascii_case(LOGIN_ALIAS) {
124
10
        oo7::dbus::Service::DEFAULT_COLLECTION.to_owned()
125
    } else {
126
8
        name.to_owned().to_lowercase()
127
    };
128

            
129
    // Use name as label (capitalized for consistency with Login)
130
8
    let label = capitalize(name);
131

            
132
    // Try to load the keyring
133
20
    let (keyring, pending_migration) = match LockedKeyring::load(path).await {
134
5
        Ok(locked_keyring) => {
135
            // Successfully loaded as v1 keyring
136
5
            if let Some(secret) = secret {
137
10
                match locked_keyring.unlock(secret.clone()).await {
138
4
                    Ok(unlocked) => {
139
8
                        tracing::info!("Unlocked keyring '{}' from {:?}", name, path);
140
5
                        (Keyring::Unlocked(unlocked), None)
141
                    }
142
4
                    Err(e) => {
143
8
                        tracing::warn!(
144
                            "Failed to unlock keyring '{}' with provided secret: {}. Keeping it locked.",
145
                            name,
146
                            e
147
                        );
148
                        // Reload as locked since unlock consumed it
149
12
                        (Keyring::Locked(LockedKeyring::load(path).await?), None)
150
                    }
151
                }
152
            } else {
153
8
                tracing::debug!("No secret provided, keeping keyring '{}' locked", name);
154
4
                (Keyring::Locked(locked_keyring), None)
155
            }
156
        }
157
4
        Err(oo7::file::Error::VersionMismatch(Some(version))) if version.first() == Some(&0) =>
158
        // v0 is the legacy version
159
        {
160
            // This is a v0 keyring that needs migration
161
            tracing::info!(
162
                "Found legacy v0 keyring '{name}' at {}, registering for migration",
163
                path.display()
164
            );
165

            
166
            let migration = PendingMigration::V0 {
167
4
                name: name.to_owned(),
168
4
                path: path.to_path_buf(),
169
4
                label: label.clone(),
170
4
                alias: alias.clone(),
171
            };
172

            
173
8
            tracing::debug!("Attempting immediate migration of v0 keyring '{name}'",);
174
12
            match migration.migrate(data_dir, secret).await {
175
4
                Ok(unlocked) => {
176
8
                    tracing::info!("Successfully migrated v0 keyring '{name}' to v1",);
177
4
                    return Ok(LoadedKeyring {
178
4
                        name: name.to_owned(),
179
4
                        label,
180
4
                        alias,
181
4
                        keyring: Keyring::Unlocked(unlocked),
182
4
                        pending_migration: None,
183
                    });
184
                }
185
4
                Err(e) => {
186
8
                    tracing::warn!(
187
                        "Failed to migrate v0 keyring '{name}': {e}. Creating locked placeholder collection.",
188
                    );
189
                }
190
            }
191

            
192
            // Migration failed - create locked placeholder and register for
193
            // pending migration
194
4
            tracing::debug!(
195
                "Creating locked placeholder for v0 keyring '{}', will migrate on unlock",
196
                name
197
            );
198

            
199
12
            let locked = LockedKeyring::open_at(data_dir, name).await?;
200
4
            (Keyring::Locked(locked), Some(migration))
201
        }
202
        // Plain legacy keyrings, written by gnome-keyring for an empty
203
        // password, don't have the binary file header. Their migration
204
        // doesn't need a secret, so if it fails this isn't a keyring.
205
        Err(oo7::file::Error::FileHeaderMismatch(_)) => {
206
8
            tracing::info!(
207
                "Found legacy plain keyring '{name}' at {}, migrating",
208
                path.display()
209
            );
210

            
211
            let migration = PendingMigration::V0 {
212
4
                name: name.to_owned(),
213
4
                path: path.to_path_buf(),
214
4
                label: label.clone(),
215
4
                alias: alias.clone(),
216
            };
217
            (
218
12
                Keyring::Unlocked(migration.migrate(data_dir, secret).await?),
219
4
                None,
220
            )
221
        }
222
        Err(e) => {
223
            return Err(e.into());
224
        }
225
    };
226

            
227
4
    Ok(LoadedKeyring {
228
4
        name: name.to_owned(),
229
4
        label,
230
4
        alias,
231
4
        keyring,
232
4
        pending_migration,
233
    })
234
}
235

            
236
/// Discover KWallet keyrings for migration
237
#[cfg(feature = "kwallet_migration")]
238
async fn discover_kwallet_keyrings(
239
    data_dir: &PathBuf,
240
    secret: Option<&Secret>,
241
    discovered: &mut Vec<LoadedKeyring>,
242
) {
243
    let kwallet_dir = data_dir.join("kwalletd");
244

            
245
    if !kwallet_dir.exists() {
246
        tracing::debug!("No kwalletd directory found, skipping KWallet discovery");
247
        return;
248
    }
249

            
250
    tracing::debug!("Scanning for KWallet files in {}", kwallet_dir.display());
251

            
252
    let Ok(mut entries) = tokio::fs::read_dir(&kwallet_dir).await else {
253
        tracing::warn!("Failed to read kwalletd directory");
254
        return;
255
    };
256

            
257
    while let Ok(Some(entry)) = entries.next_entry().await {
258
        let path = entry.path();
259

            
260
        // Only process .kwl files
261
        if path.extension().is_none_or(|ext| ext != "kwl") {
262
            continue;
263
        }
264

            
265
        if migration::stamp_path(&path).exists() {
266
            continue;
267
        }
268

            
269
        let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
270
            continue;
271
        };
272

            
273
        tracing::debug!("Found KWallet file: {name}");
274

            
275
        // Use lowercased name as alias
276
        let alias = name.to_lowercase();
277

            
278
        let label = capitalize(name);
279

            
280
        let migration = PendingMigration::KWallet {
281
            name: name.to_owned(),
282
            path: path.clone(),
283
            label: label.clone(),
284
            alias: alias.clone(),
285
        };
286

            
287
        if let Some(secret) = secret {
288
            tracing::debug!("Attempting immediate migration of KWallet keyring '{name}'",);
289
            match migration.migrate(data_dir, Some(secret)).await {
290
                Ok(unlocked) => {
291
                    tracing::info!("Successfully migrated KWallet keyring '{name}' to oo7",);
292
                    discovered.push(LoadedKeyring {
293
                        name: name.to_owned(),
294
                        label,
295
                        alias,
296
                        keyring: Keyring::Unlocked(unlocked),
297
                        pending_migration: None,
298
                    });
299
                    continue;
300
                }
301
                Err(e) => {
302
                    tracing::warn!(
303
                        "Failed to migrate KWallet keyring '{name}' at {}: {e}. Creating locked placeholder collection.",
304
                        migration.path().display()
305
                    );
306
                }
307
            }
308
        }
309

            
310
        // Migration failed or no secret - create locked placeholder and
311
        // register for pending migration
312
        tracing::debug!(
313
            "Creating locked placeholder for KWallet keyring '{name}', will migrate on unlock",
314
        );
315

            
316
        match LockedKeyring::open_at(data_dir, name).await {
317
            Ok(locked) => {
318
                tracing::debug!(
319
                    "Created locked placeholder for '{name}', adding to pending migrations",
320
                );
321
                discovered.push(LoadedKeyring {
322
                    name: name.to_owned(),
323
                    label,
324
                    alias,
325
                    keyring: Keyring::Locked(locked),
326
                    pending_migration: Some(migration),
327
                });
328
            }
329
            Err(e) => {
330
                tracing::error!("Failed to create placeholder keyring for '{name}': {e}");
331
            }
332
        }
333
    }
334
}