1
//! Keyring migration support for legacy formats
2

            
3
use std::path::{Path, PathBuf};
4

            
5
use oo7::{Secret, file::UnlockedKeyring};
6

            
7
use crate::error::Error;
8

            
9
/// Returns the stamp file path for a migrated keyring file.
10
4
pub fn stamp_path(path: &Path) -> PathBuf {
11
4
    let mut stamped = path.as_os_str().to_owned();
12
4
    stamped.push(".migrated");
13
4
    PathBuf::from(stamped)
14
}
15

            
16
/// Pending keyring migration
17
#[derive(Clone)]
18
pub enum PendingMigration {
19
    /// Legacy v0 keyring format
20
    V0 {
21
        name: String,
22
        path: PathBuf,
23
        label: String,
24
        alias: String,
25
    },
26
    /// KWallet keyring format
27
    #[cfg(feature = "kwallet_migration")]
28
    KWallet {
29
        name: String,
30
        path: PathBuf,
31
        label: String,
32
        alias: String,
33
    },
34
}
35

            
36
impl PendingMigration {
37
    /// Check whether the secret can decrypt the legacy keyring, as the
38
    /// placeholder keyring of a pending migration accepts any secret.
39
16
    pub async fn validate_secret(&self, secret: &Secret) -> Result<bool, Error> {
40
        match self {
41
4
            Self::V0 { path, .. } => {
42
16
                let content = tokio::fs::read(path).await?;
43
8
                let keyring = oo7::file::api::LegacyKeyring::try_from(content.as_slice())?;
44
8
                Ok(keyring.validate_secret(secret)?)
45
            }
46
            #[cfg(feature = "kwallet_migration")]
47
            Self::KWallet { path, .. } => {
48
                let path = path.clone();
49
                let password = secret.to_vec();
50
                match tokio::task::spawn_blocking(move || {
51
                    kwallet_parser::KWalletFile::open(&path, &password)
52
                })
53
                .await
54
                {
55
                    Ok(Ok(_)) => Ok(true),
56
                    Ok(Err(err)) => {
57
                        tracing::debug!("Failed to validate KWallet keyring secret: {err}");
58
                        Ok(false)
59
                    }
60
                    Err(err) => Err(Error::IO(std::io::Error::other(format!(
61
                        "Task join error: {err}"
62
                    )))),
63
                }
64
            }
65
        }
66
    }
67

            
68
    /// The placeholder items of the legacy keyring, exposing its
69
    /// cleartext attributes so they can be searched while the keyring
70
    /// is locked.
71
16
    pub async fn items(&self) -> Result<Vec<oo7::file::Item>, Error> {
72
        match self {
73
4
            Self::V0 { path, .. } => {
74
16
                let content = tokio::fs::read(path).await?;
75
8
                let keyring = oo7::file::api::LegacyKeyring::try_from(content.as_slice())?;
76
8
                Ok(keyring.items())
77
            }
78
            #[cfg(feature = "kwallet_migration")]
79
            Self::KWallet { .. } => Ok(Vec::new()),
80
        }
81
    }
82

            
83
    /// Attempt to migrate this keyring with the provided secret
84
4
    pub async fn migrate(
85
        &self,
86
        data_dir: &PathBuf,
87
        secret: Option<&Secret>,
88
    ) -> Result<UnlockedKeyring, Error> {
89
        match self {
90
4
            Self::V0 { path, name, .. } => {
91
8
                tracing::debug!("Migrating v0 keyring: {}", name);
92

            
93
20
                let unlocked = UnlockedKeyring::open_at(data_dir, name, secret.cloned()).await?;
94

            
95
                // Write migrated keyring
96
12
                unlocked.write().await?;
97
4
                tracing::info!("Wrote migrated keyring '{}' to disk", name);
98

            
99
16
                if let Err(e) = tokio::fs::write(stamp_path(path), b"").await {
100
                    tracing::warn!("Failed to write migration stamp for {:?}: {}", path, e);
101
                }
102

            
103
8
                tracing::info!("Successfully migrated v0 keyring '{}'", name);
104
4
                Ok(unlocked)
105
            }
106
            #[cfg(feature = "kwallet_migration")]
107
            Self::KWallet { path, name, .. } => {
108
                tracing::debug!("Migrating KWallet keyring: {}", name);
109

            
110
                let secret = secret.ok_or_else(|| {
111
                    Error::IO(std::io::Error::other("KWallet migration requires a secret"))
112
                })?;
113

            
114
                // Parse KWallet file in blocking task
115
                let path_clone = path.clone();
116
                let password = secret.to_vec();
117
                let wallet = tokio::task::spawn_blocking(move || {
118
                    kwallet_parser::KWalletFile::open(&path_clone, &password)
119
                })
120
                .await
121
                .map_err(|e| {
122
                    Error::IO(std::io::Error::other(format!("Task join error: {}", e)))
123
                })??;
124

            
125
                tracing::info!("Parsed KWallet file '{}'", name);
126

            
127
                // Create new oo7 keyring
128
                let unlocked =
129
                    UnlockedKeyring::open_at(data_dir, name, Some(secret.clone())).await?;
130

            
131
                // Convert KWallet entries to oo7 items
132
                let mut items = Vec::new();
133
                for (folder_name, folder) in wallet.wallet() {
134
                    for (entry_key, entry) in folder {
135
                        match kwallet_parser::convert_entry(folder_name, entry_key, entry) {
136
                            Ok(ss_entry) => {
137
                                items.push((
138
                                    ss_entry.label().to_owned(),
139
                                    ss_entry.attributes().to_owned(),
140
                                    Secret::blob(ss_entry.secret()),
141
                                    true,
142
                                ));
143
                            }
144
                            Err(e) => {
145
                                tracing::warn!(
146
                                    "Skipping entry {}/{}: {}",
147
                                    folder_name,
148
                                    entry_key,
149
                                    e
150
                                );
151
                            }
152
                        }
153
                    }
154
                }
155
                unlocked.create_items(items).await?;
156

            
157
                tracing::info!("Migrated KWallet entries to oo7 format for '{}'", name);
158

            
159
                if let Err(e) = tokio::fs::write(stamp_path(path), b"").await {
160
                    tracing::warn!("Failed to write migration stamp for {:?}: {}", path, e);
161
                }
162

            
163
                tracing::info!("Successfully migrated KWallet keyring '{}'", name);
164
                Ok(unlocked)
165
            }
166
        }
167
    }
168

            
169
4
    pub fn name(&self) -> &str {
170
        match self {
171
4
            Self::V0 { name, .. } => name,
172
            #[cfg(feature = "kwallet_migration")]
173
            Self::KWallet { name, .. } => name,
174
        }
175
    }
176

            
177
    pub fn label(&self) -> &str {
178
        match self {
179
            Self::V0 { label, .. } => label,
180
            #[cfg(feature = "kwallet_migration")]
181
            Self::KWallet { label, .. } => label,
182
        }
183
    }
184

            
185
    pub fn alias(&self) -> &str {
186
        match self {
187
            Self::V0 { alias, .. } => alias,
188
            #[cfg(feature = "kwallet_migration")]
189
            Self::KWallet { alias, .. } => alias,
190
        }
191
    }
192

            
193
    pub fn path(&self) -> &PathBuf {
194
        match self {
195
            Self::V0 { path, .. } => path,
196
            #[cfg(feature = "kwallet_migration")]
197
            Self::KWallet { path, .. } => path,
198
        }
199
    }
200
}