|
| 1 | +use std::{collections::BTreeSet, fs, io}; |
| 2 | + |
| 3 | +use serde::{Deserialize, Serialize}; |
| 4 | +use tauri::AppHandle; |
| 5 | + |
| 6 | +use super::{ |
| 7 | + atomic_write_json_restricted, delete_secrets, is_lower_hex, reject_unsafe_owner_file, |
| 8 | + workspace_connection_dir, ProjectConnectionScope, ProjectConnectionStore, |
| 9 | +}; |
| 10 | + |
| 11 | +const CREDENTIAL_JOURNAL_VERSION: u32 = 1; |
| 12 | +const MAX_JOURNALED_GENERATIONS: usize = 2; |
| 13 | + |
| 14 | +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 15 | +#[serde(deny_unknown_fields, rename_all = "camelCase")] |
| 16 | +struct CredentialJournal { |
| 17 | + version: u32, |
| 18 | + connection_id: String, |
| 19 | + generations: Vec<String>, |
| 20 | +} |
| 21 | + |
| 22 | +fn journal_path( |
| 23 | + app: &AppHandle, |
| 24 | + scope: &ProjectConnectionScope, |
| 25 | +) -> Result<std::path::PathBuf, String> { |
| 26 | + Ok(workspace_connection_dir(app, scope)?.join("credential-journal.json")) |
| 27 | +} |
| 28 | + |
| 29 | +fn validate_journal(journal: &CredentialJournal) -> Result<(), String> { |
| 30 | + if journal.version != CREDENTIAL_JOURNAL_VERSION |
| 31 | + || !is_lower_hex(&journal.connection_id, 32) |
| 32 | + || journal.generations.is_empty() |
| 33 | + || journal.generations.len() > MAX_JOURNALED_GENERATIONS |
| 34 | + || journal |
| 35 | + .generations |
| 36 | + .iter() |
| 37 | + .any(|generation| !is_lower_hex(generation, 32)) |
| 38 | + || journal.generations.iter().collect::<BTreeSet<_>>().len() != journal.generations.len() |
| 39 | + { |
| 40 | + return Err("Project connection credential recovery data is invalid.".to_string()); |
| 41 | + } |
| 42 | + Ok(()) |
| 43 | +} |
| 44 | + |
| 45 | +fn generations_to_delete( |
| 46 | + journal: &CredentialJournal, |
| 47 | + store: &ProjectConnectionStore, |
| 48 | +) -> Vec<String> { |
| 49 | + let referenced = store |
| 50 | + .connections |
| 51 | + .iter() |
| 52 | + .find(|connection| connection.id == journal.connection_id) |
| 53 | + .filter(|connection| !connection.env_keys.is_empty()) |
| 54 | + .map(|connection| connection.credential_generation.as_str()); |
| 55 | + journal |
| 56 | + .generations |
| 57 | + .iter() |
| 58 | + .filter(|generation| Some(generation.as_str()) != referenced) |
| 59 | + .cloned() |
| 60 | + .collect() |
| 61 | +} |
| 62 | + |
| 63 | +pub(super) fn begin( |
| 64 | + app: &AppHandle, |
| 65 | + scope: &ProjectConnectionScope, |
| 66 | + connection_id: &str, |
| 67 | + generations: Vec<String>, |
| 68 | +) -> Result<(), String> { |
| 69 | + let journal = CredentialJournal { |
| 70 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 71 | + connection_id: connection_id.to_string(), |
| 72 | + generations, |
| 73 | + }; |
| 74 | + validate_journal(&journal)?; |
| 75 | + let path = journal_path(app, scope)?; |
| 76 | + reject_unsafe_owner_file(&path)?; |
| 77 | + let bytes = serde_json::to_vec_pretty(&journal) |
| 78 | + .map_err(|error| format!("failed to prepare credential recovery data: {error}"))?; |
| 79 | + atomic_write_json_restricted(&path, &bytes) |
| 80 | +} |
| 81 | + |
| 82 | +pub(super) fn complete(app: &AppHandle, scope: &ProjectConnectionScope) -> Result<(), String> { |
| 83 | + let path = journal_path(app, scope)?; |
| 84 | + complete_path(&path) |
| 85 | +} |
| 86 | + |
| 87 | +fn complete_path(path: &std::path::Path) -> Result<(), String> { |
| 88 | + reject_unsafe_owner_file(path)?; |
| 89 | + match fs::remove_file(path) { |
| 90 | + Ok(()) => Ok(()), |
| 91 | + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), |
| 92 | + Err(error) => Err(format!( |
| 93 | + "failed to clear Project connection credential recovery data: {error}" |
| 94 | + )), |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +pub(super) fn reconcile( |
| 99 | + app: &AppHandle, |
| 100 | + scope: &ProjectConnectionScope, |
| 101 | + store: &ProjectConnectionStore, |
| 102 | +) -> Result<(), String> { |
| 103 | + let path = journal_path(app, scope)?; |
| 104 | + reconcile_path(&path, store, |connection_id, generation| { |
| 105 | + delete_secrets(app, scope, connection_id, generation) |
| 106 | + }) |
| 107 | +} |
| 108 | + |
| 109 | +fn reconcile_path( |
| 110 | + path: &std::path::Path, |
| 111 | + store: &ProjectConnectionStore, |
| 112 | + mut delete_generation: impl FnMut(&str, &str) -> Result<(), String>, |
| 113 | +) -> Result<(), String> { |
| 114 | + reject_unsafe_owner_file(path)?; |
| 115 | + let bytes = match fs::read(path) { |
| 116 | + Ok(bytes) => bytes, |
| 117 | + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), |
| 118 | + Err(error) => { |
| 119 | + return Err(format!( |
| 120 | + "failed to read Project connection credential recovery data: {error}" |
| 121 | + )); |
| 122 | + } |
| 123 | + }; |
| 124 | + let journal: CredentialJournal = serde_json::from_slice(&bytes) |
| 125 | + .map_err(|_| "Project connection credential recovery data is invalid.".to_string())?; |
| 126 | + validate_journal(&journal)?; |
| 127 | + for generation in generations_to_delete(&journal, store) { |
| 128 | + delete_generation(&journal.connection_id, &generation)?; |
| 129 | + } |
| 130 | + complete_path(path) |
| 131 | +} |
| 132 | + |
| 133 | +#[cfg(test)] |
| 134 | +mod tests { |
| 135 | + use super::*; |
| 136 | + use crate::managed_agents::project_connections::{ |
| 137 | + next_generation, ProjectConnectionHealth, StoredProjectConnection, CONNECTION_STORE_VERSION, |
| 138 | + }; |
| 139 | + |
| 140 | + fn connection(generation: &str) -> StoredProjectConnection { |
| 141 | + StoredProjectConnection { |
| 142 | + id: "c".repeat(32), |
| 143 | + project_scope: ProjectConnectionScope { |
| 144 | + relay_url: "ws://127.0.0.1:3000".to_string(), |
| 145 | + operator_pubkey: "a".repeat(64), |
| 146 | + project_address: format!("30621:{}:portable-agents", "a".repeat(64)), |
| 147 | + }, |
| 148 | + name: "Test".to_string(), |
| 149 | + provider: "Fixture".to_string(), |
| 150 | + capability_ids: Vec::new(), |
| 151 | + command: "/usr/bin/true".to_string(), |
| 152 | + args: Vec::new(), |
| 153 | + env_keys: vec!["TOKEN".to_string()], |
| 154 | + discovered_tools: Vec::new(), |
| 155 | + health: ProjectConnectionHealth::default(), |
| 156 | + executable_sha256: "d".repeat(64), |
| 157 | + generation: next_generation(), |
| 158 | + credential_generation: generation.to_string(), |
| 159 | + created_at: "2026-08-05T00:00:00Z".to_string(), |
| 160 | + updated_at: "2026-08-05T00:00:00Z".to_string(), |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + fn store(connection: Option<StoredProjectConnection>) -> ProjectConnectionStore { |
| 165 | + ProjectConnectionStore { |
| 166 | + version: CONNECTION_STORE_VERSION, |
| 167 | + connections: connection.into_iter().collect(), |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn restart_reconciliation_deletes_only_unreferenced_generations() { |
| 173 | + let old = "a".repeat(32); |
| 174 | + let new = "b".repeat(32); |
| 175 | + let cases = [ |
| 176 | + ( |
| 177 | + "create interrupted after credential write", |
| 178 | + CredentialJournal { |
| 179 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 180 | + connection_id: "c".repeat(32), |
| 181 | + generations: vec![new.clone()], |
| 182 | + }, |
| 183 | + store(None), |
| 184 | + vec![new.clone()], |
| 185 | + ), |
| 186 | + ( |
| 187 | + "update interrupted before metadata swap", |
| 188 | + CredentialJournal { |
| 189 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 190 | + connection_id: "c".repeat(32), |
| 191 | + generations: vec![old.clone(), new.clone()], |
| 192 | + }, |
| 193 | + store(Some(connection(&old))), |
| 194 | + vec![new.clone()], |
| 195 | + ), |
| 196 | + ( |
| 197 | + "update interrupted after metadata swap", |
| 198 | + CredentialJournal { |
| 199 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 200 | + connection_id: "c".repeat(32), |
| 201 | + generations: vec![old.clone(), new.clone()], |
| 202 | + }, |
| 203 | + store(Some(connection(&new))), |
| 204 | + vec![old.clone()], |
| 205 | + ), |
| 206 | + ( |
| 207 | + "delete interrupted after metadata removal", |
| 208 | + CredentialJournal { |
| 209 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 210 | + connection_id: "c".repeat(32), |
| 211 | + generations: vec![old.clone()], |
| 212 | + }, |
| 213 | + store(None), |
| 214 | + vec![old.clone()], |
| 215 | + ), |
| 216 | + ]; |
| 217 | + |
| 218 | + for (name, journal, store, expected) in cases { |
| 219 | + assert_eq!(generations_to_delete(&journal, &store), expected, "{name}"); |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + #[test] |
| 224 | + fn reconciliation_retries_cleanup_before_removing_the_journal() { |
| 225 | + let old = "a".repeat(32); |
| 226 | + let new = "b".repeat(32); |
| 227 | + let cases = [ |
| 228 | + ( |
| 229 | + CredentialJournal { |
| 230 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 231 | + connection_id: "c".repeat(32), |
| 232 | + generations: vec![new.clone()], |
| 233 | + }, |
| 234 | + store(None), |
| 235 | + new.clone(), |
| 236 | + ), |
| 237 | + ( |
| 238 | + CredentialJournal { |
| 239 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 240 | + connection_id: "c".repeat(32), |
| 241 | + generations: vec![old.clone(), new.clone()], |
| 242 | + }, |
| 243 | + store(Some(connection(&old))), |
| 244 | + new.clone(), |
| 245 | + ), |
| 246 | + ( |
| 247 | + CredentialJournal { |
| 248 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 249 | + connection_id: "c".repeat(32), |
| 250 | + generations: vec![old.clone(), new.clone()], |
| 251 | + }, |
| 252 | + store(Some(connection(&new))), |
| 253 | + old.clone(), |
| 254 | + ), |
| 255 | + ( |
| 256 | + CredentialJournal { |
| 257 | + version: CREDENTIAL_JOURNAL_VERSION, |
| 258 | + connection_id: "c".repeat(32), |
| 259 | + generations: vec![old.clone()], |
| 260 | + }, |
| 261 | + store(None), |
| 262 | + old.clone(), |
| 263 | + ), |
| 264 | + ]; |
| 265 | + |
| 266 | + for (journal, store, orphan) in cases { |
| 267 | + let dir = tempfile::tempdir().unwrap(); |
| 268 | + let path = dir.path().join("credential-journal.json"); |
| 269 | + let bytes = serde_json::to_vec_pretty(&journal).unwrap(); |
| 270 | + atomic_write_json_restricted(&path, &bytes).unwrap(); |
| 271 | + |
| 272 | + let error = |
| 273 | + reconcile_path(&path, &store, |_, _| Err("keyring unavailable".to_string())) |
| 274 | + .unwrap_err(); |
| 275 | + assert_eq!(error, "keyring unavailable"); |
| 276 | + assert!(path.exists(), "failed cleanup must preserve recovery data"); |
| 277 | + |
| 278 | + let mut deleted = Vec::new(); |
| 279 | + reconcile_path(&path, &store, |connection_id, generation| { |
| 280 | + deleted.push((connection_id.to_string(), generation.to_string())); |
| 281 | + Ok(()) |
| 282 | + }) |
| 283 | + .unwrap(); |
| 284 | + assert_eq!(deleted, [(journal.connection_id.clone(), orphan)]); |
| 285 | + assert!(!path.exists(), "successful retry must clear recovery data"); |
| 286 | + } |
| 287 | + } |
| 288 | +} |
0 commit comments