1
use oo7::{Secret, dbus::ServiceError, file::Keyring};
2
use zbus::{
3
    proxy::Defaults,
4
    wire::{ObjectPath, OwnedObjectPath},
5
};
6

            
7
use super::Service;
8
use crate::{collection::Collection, error::custom_service_error, migration::PendingMigration};
9

            
10
impl Service {
11
10
    pub async fn set_locked(
12
        &self,
13
        locked: bool,
14
        objects: &[OwnedObjectPath],
15
    ) -> Result<(Vec<OwnedObjectPath>, Vec<OwnedObjectPath>), ServiceError> {
16
10
        let mut without_prompt = Vec::new();
17
10
        let mut with_prompt = Vec::new();
18
20
        let snapshot = self.sorted_collections().await;
19

            
20
40
        for object in objects {
21
53
            let resolved = Self::resolve_alias(&snapshot, object)
22
43
                .await
23
44
                .unwrap_or_else(|| object.clone());
24
11
            let mut found = false;
25
22
            for collection in &snapshot {
26
22
                let collection_locked = collection.is_locked().await;
27
11
                if resolved.as_str() == collection.path().as_str() {
28
8
                    found = true;
29
8
                    if collection_locked == locked {
30
9
                        tracing::debug!(
31
                            "Collection: {} is already {}.",
32
                            resolved,
33
                            if locked { "locked" } else { "unlocked" }
34
                        );
35
12
                        without_prompt.push(resolved.clone());
36
8
                    } else if locked {
37
                        // Locking never requires a prompt
38
25
                        collection.set_locked(true, None).await?;
39
8
                        without_prompt.push(resolved.clone());
40
                    } else {
41
                        // Unlocking may require a prompt
42
16
                        with_prompt.push(resolved.clone());
43
                    }
44
                    break;
45
24
                } else if let Some(item) = collection.item_from_path(&resolved).await {
46
8
                    found = true;
47
                    // If collection is locked, can't perform any item
48
                    // lock/unlock operations
49
8
                    if collection_locked {
50
                        // Unlocking an item when collection is locked requires
51
                        // unlocking collection
52
6
                        if !locked {
53
8
                            with_prompt.push(resolved.clone());
54
                        } else {
55
                            // Can't lock an item when collection is locked
56
4
                            return Err(ServiceError::IsLocked(format!(
57
                                "Cannot lock item {} when collection is locked",
58
                                resolved
59
                            )));
60
                        }
61
24
                    } else if locked == item.is_locked().await {
62
11
                        tracing::debug!(
63
                            "Item: {} is already {}.",
64
                            resolved,
65
                            if locked { "locked" } else { "unlocked" }
66
                        );
67
12
                        without_prompt.push(resolved.clone());
68
                    } else {
69
24
                        let keyring = collection.keyring.read().await;
70
8
                        match keyring.as_ref() {
71
16
                            Some(k) if !k.is_locked() => {
72
24
                                item.set_locked(locked, k.as_unlocked()).await?;
73
8
                                without_prompt.push(resolved.clone());
74
                            }
75
                            _ => {
76
                                if locked {
77
                                    return Err(ServiceError::IsLocked(format!(
78
                                        "Cannot lock item {} when collection is locked",
79
                                        resolved
80
                                    )));
81
                                } else {
82
                                    with_prompt.push(resolved.clone());
83
                                }
84
                            }
85
                        }
86
                    }
87
                    break;
88
                }
89
            }
90
10
            if !found {
91
8
                tracing::warn!("Object: {} does not exist.", object);
92
            }
93
        }
94

            
95
10
        Ok((without_prompt, with_prompt))
96
    }
97

            
98
8
    pub(crate) async fn collection_for_objects(
99
        &self,
100
        objects: &[OwnedObjectPath],
101
    ) -> Option<Collection> {
102
32
        for object in objects {
103
24
            if let Some(collection) = self.collection_from_path(object).await {
104
8
                return Some(collection);
105
            }
106
        }
107

            
108
        // Fall back to the parent path of the first item
109
4
        let parent = objects.first()?.as_str().rsplit_once('/')?.0;
110
12
        self.collection_from_path(&ObjectPath::try_from(parent).ok()?)
111
8
            .await
112
    }
113

            
114
    /// Unlock a collection with a secret, completing its pending legacy
115
    /// keyring migration, if any.
116
    ///
117
    /// Unlike [`Collection::set_locked`], this migrates the legacy keyring
118
    /// registered for the collection instead of unlocking the empty
119
    /// placeholder backing it, and fails if the secret cannot decrypt it.
120
8
    pub(crate) async fn unlock_collection(
121
        &self,
122
        collection: &Collection,
123
        secret: Option<Secret>,
124
    ) -> Result<(), ServiceError> {
125
        let migration = {
126
16
            let pending = self.pending_migrations.lock().await;
127
16
            pending.get(collection.name()).cloned()
128
        };
129

            
130
8
        let Some(migration) = migration else {
131
16
            return collection.set_locked(false, secret).await;
132
        };
133

            
134
8
        let name = migration.name().to_owned();
135
8
        tracing::debug!("Attempting migration for '{name}' during unlock");
136
12
        match migration.migrate(&self.data_dir, secret.as_ref()).await {
137
4
            Ok(unlocked) => {
138
8
                tracing::info!("Successfully migrated '{name}' during unlock");
139

            
140
20
                collection
141
4
                    .apply_migrated_keyring(Keyring::Unlocked(unlocked))
142
16
                    .await
143
8
                    .map_err(|e| {
144
                        custom_service_error(&format!(
145
                            "Failed to dispatch items of migrated keyring '{name}': {e}"
146
                        ))
147
                    })?;
148

            
149
4
                self.pending_migrations.lock().await.remove(&name);
150
4
                Ok(())
151
            }
152
12
            Err(e) => Err(custom_service_error(&format!(
153
                "Failed to migrate keyring '{name}': {e}"
154
            ))),
155
        }
156
    }
157

            
158
    /// Whether a legacy keyring awaits migration under this collection's
159
    /// name.
160
78
    pub(crate) async fn has_pending_migration(&self, name: &str) -> bool {
161
39
        self.pending_migrations.lock().await.contains_key(name)
162
    }
163

            
164
40
    pub(crate) async fn perform_unlock(&self, objects: &[OwnedObjectPath], secret: Option<Secret>) {
165
32
        for object in objects {
166
            let collection = {
167
24
                let collections = self.collections.lock().await;
168
16
                collections.get(object).cloned()
169
            };
170

            
171
8
            if let Some(collection) = collection {
172
28
                if let Err(e) = self.unlock_collection(&collection, secret.clone()).await {
173
8
                    tracing::warn!("Failed to unlock collection {}: {}", collection.path(), e);
174
                }
175
            } else {
176
                // Try to find as item within collections
177
12
                let collections = self.collections.lock().await;
178
4
                let mut found_collection = None;
179
8
                for collection in collections.values() {
180
12
                    if let Some(item) = collection.item_from_path(object).await {
181
4
                        found_collection = Some((
182
4
                            collection.clone(),
183
4
                            item.clone(),
184
12
                            collection.is_locked().await,
185
                        ));
186
                        break;
187
                    }
188
                }
189
4
                drop(collections);
190

            
191
4
                if let Some((collection, item, is_locked)) = found_collection {
192
4
                    if is_locked {
193
16
                        if let Err(e) = self.unlock_collection(&collection, secret.clone()).await {
194
                            tracing::warn!(
195
                                "Failed to unlock collection {}: {}",
196
                                collection.path(),
197
                                e
198
                            );
199
                        }
200
                    } else {
201
                        let keyring = collection.keyring.read().await;
202
                        match keyring.as_ref() {
203
                            Some(k) if !k.is_locked() => {
204
                                let _ = item.set_locked(false, k.as_unlocked()).await;
205
                            }
206
                            _ => {
207
                                drop(keyring);
208
                                if let Err(e) =
209
                                    self.unlock_collection(&collection, secret.clone()).await
210
                                {
211
                                    tracing::warn!(
212
                                        "Failed to unlock collection {}: {}",
213
                                        collection.path(),
214
                                        e
215
                                    );
216
                                }
217
                            }
218
                        }
219
                    }
220
                }
221
            }
222
        }
223

            
224
8
        let mut pending = self.pending_unlocks.lock().await;
225
16
        for obj in objects {
226
16
            pending.remove(obj);
227
        }
228
    }
229

            
230
24
    pub async fn migrate_pending_keyrings(&self, secret: &Secret) -> Vec<String> {
231
4
        let mut migrated = Vec::new();
232
        // Migrating reads files and derives keys, don't hold the lock for it
233
20
        let migrations: Vec<PendingMigration> = self
234
            .pending_migrations
235
            .lock()
236
12
            .await
237
            .values()
238
            .cloned()
239
            .collect();
240
4
        let mut to_remove = Vec::new();
241

            
242
12
        for migration in &migrations {
243
8
            let name = migration.name();
244
4
            tracing::debug!("Attempting to migrate pending keyring: {name}");
245

            
246
16
            match migration.migrate(&self.data_dir, Some(secret)).await {
247
4
                Ok(unlocked) => {
248
                    // Look for the placeholder collection that was registered
249
                    // at startup.
250
                    let placeholder = {
251
8
                        let collections = self.collections.lock().await;
252
16
                        collections.values().find(|c| c.name() == name).cloned()
253
                    };
254

            
255
4
                    if let Some(collection) = placeholder {
256
12
                        if let Err(e) = collection
257
4
                            .apply_migrated_keyring(Keyring::Unlocked(unlocked))
258
20
                            .await
259
                        {
260
                            tracing::error!(
261
                                "Failed to dispatch items for migrated keyring '{name}': {e}",
262
                            );
263
                            continue;
264
                        }
265

            
266
8
                        if let Ok(signal_emitter) =
267
                            self.signal_emitter(oo7::dbus::api::Service::PATH.as_ref().unwrap())
268
                        {
269
12
                            let _ = self.collections_changed(&signal_emitter).await;
270
                        }
271

            
272
8
                        tracing::info!(
273
                            "Replaced placeholder for keyring '{name}' with migrated data",
274
                        );
275
                    } else {
276
                        let label = migration.label();
277
                        let alias = migration.alias();
278

            
279
                        let collection = match self
280
                            .register_collection(name, label, alias, Keyring::Unlocked(unlocked))
281
                            .await
282
                        {
283
                            Ok((_, collection)) => collection,
284
                            Err(e) => {
285
                                tracing::error!(
286
                                    "Failed to register migrated collection '{name}': {e}",
287
                                );
288
                                continue;
289
                            }
290
                        };
291

            
292
                        if let Err(e) = collection.dispatch_items().await {
293
                            tracing::error!(
294
                                "Failed to dispatch items for migrated collection '{name}': {e}",
295
                            );
296
                        }
297
                    }
298

            
299
4
                    migrated.push(name.to_owned());
300
5
                    to_remove.push(name.to_owned());
301
                }
302
4
                Err(e) => {
303
4
                    tracing::debug!(
304
                        "Failed to migrate keyring '{name}' found at {} with provided secret: {e}",
305
                        migration.path().display()
306
                    );
307
                }
308
            }
309
        }
310

            
311
4
        let mut pending = self.pending_migrations.lock().await;
312
8
        for name in &to_remove {
313
10
            pending.remove(name);
314
        }
315

            
316
4
        migrated
317
    }
318
}