fido 0.2.3

A blazing-fast, keyboard-driven social platform for developers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use anyhow::{Context, Result};
use std::fs;
use std::io::Write;
use std::path::PathBuf;

/// Manages session token storage in the user's home directory.
///
/// The session token is stored in `~/.fido/session` with 0600 permissions
/// to ensure only the owner can read/write the file.
#[derive(Debug, Clone)]
pub struct SessionStore {
    file_path: PathBuf,
    legacy_file_path: Option<PathBuf>,
}

impl SessionStore {
    /// Creates a new SessionStore with the default path `~/.fido/session`.
    ///
    /// # Returns
    ///
    /// Returns an error if the home directory cannot be determined.
    #[cfg(not(test))]
    pub fn new() -> Result<Self> {
        let home_dir = dirs::home_dir().context("Failed to determine home directory")?;

        let fido_dir = home_dir.join(".fido");
        let file_path = fido_dir.join("session");

        Ok(Self {
            file_path,
            legacy_file_path: None,
        })
    }

    /// Creates a new SessionStore with a temp directory for tests.
    #[cfg(test)]
    pub fn new() -> Result<Self> {
        let pid = std::process::id();
        let fido_dir = std::env::temp_dir().join(format!("fido-test-{}", pid));
        let file_path = fido_dir.join("session");
        Ok(Self {
            file_path,
            legacy_file_path: None,
        })
    }

    /// Creates a session store scoped to a specific server URL.
    ///
    /// Session tokens are server-side credentials, so a token issued by one
    /// Fido server must not overwrite or invalidate the token for another.
    #[cfg(not(test))]
    pub fn for_server(server_url: &str) -> Result<Self> {
        let home_dir = dirs::home_dir().context("Failed to determine home directory")?;
        Self::for_server_in_dir(home_dir.join(".fido"), server_url)
    }

    #[cfg(test)]
    pub fn for_server(server_url: &str) -> Result<Self> {
        let pid = std::process::id();
        Self::for_server_in_dir(
            std::env::temp_dir().join(format!("fido-test-{}", pid)),
            server_url,
        )
    }

    fn for_server_in_dir(fido_dir: PathBuf, server_url: &str) -> Result<Self> {
        let scope = server_scope_key(server_url);
        let file_path = fido_dir.join(format!("session_{}", scope));
        let legacy_file_path = Some(fido_dir.join("session"));

        Ok(Self {
            file_path,
            legacy_file_path,
        })
    }

    #[cfg(test)]
    fn for_server_in_test_dir(fido_dir: PathBuf, server_url: &str) -> Self {
        Self::for_server_in_dir(fido_dir, server_url).unwrap()
    }

    /// Loads the session token from the file.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(token))` if the file exists and contains a valid token
    /// - `Ok(None)` if the file doesn't exist
    /// - `Err(_)` if the file is corrupted or cannot be read
    pub fn load(&self) -> Result<Option<String>> {
        let file_path = if self.file_path.exists() {
            self.file_path.clone()
        } else if let Some(legacy_file_path) = &self.legacy_file_path {
            if legacy_file_path.exists() {
                legacy_file_path.clone()
            } else {
                return Ok(None);
            }
        } else {
            return Ok(None);
        };

        let content = fs::read_to_string(&file_path).context("Failed to read session file")?;

        // Validate session file format
        let token = content.trim();

        if token.is_empty() {
            log::warn!("Session file is empty, treating as no session");
            return Ok(None);
        }

        // Basic validation: session tokens should be reasonable length
        // UUIDs are 36 chars, but we allow flexibility for different token formats
        if token.len() < 8 || token.len() > 256 {
            log::warn!(
                "Session token has invalid length: {}, treating as corrupted",
                token.len()
            );
            return Ok(None);
        }

        // Check for obviously corrupted content (binary data, control characters, etc.)
        if token
            .chars()
            .any(|c| c.is_control() && c != '\n' && c != '\r' && c != '\t')
        {
            log::warn!("Session file contains control characters, treating as corrupted");
            return Ok(None);
        }

        log::debug!(
            "Successfully loaded session token from {}",
            file_path.display()
        );
        let token = token.to_string();

        // Migrate legacy ~/.fido/session into the server-scoped file on first
        // successful read. After this, local/dev and production sessions no
        // longer clobber each other.
        if file_path != self.file_path {
            self.save(&token)?;
            if let Err(e) = fs::remove_file(&file_path) {
                log::warn!(
                    "Failed to remove legacy session file {}: {}",
                    file_path.display(),
                    e
                );
            }
        }

        Ok(Some(token))
    }

    /// Saves the session token to the file with 0600 permissions.
    ///
    /// This method:
    /// - Creates the `.fido` directory if it doesn't exist
    /// - Removes any old/stale session files
    /// - Uses atomic writes to prevent partial writes
    /// - Sets file permissions to 0600 (owner read/write only)
    ///
    /// # Arguments
    ///
    /// * `token` - The session token to save
    pub fn save(&self, token: &str) -> Result<()> {
        // Ensure the .fido directory exists
        if let Some(parent) = self.file_path.parent() {
            fs::create_dir_all(parent).context("Failed to create .fido directory")?;
        }

        // Remove any old/stale session files before saving
        self.cleanup_old_files()?;

        // Use atomic write: write to temporary file, then rename
        let temp_path = self.file_path.with_extension("tmp");

        // Write to temporary file
        let mut file =
            fs::File::create(&temp_path).context("Failed to create temporary session file")?;

        file.write_all(token.as_bytes())
            .context("Failed to write session token")?;

        file.sync_all()
            .context("Failed to sync session file to disk")?;

        drop(file);

        // Set permissions to 0600 (owner read/write only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let permissions = fs::Permissions::from_mode(0o600);
            fs::set_permissions(&temp_path, permissions)
                .context("Failed to set session file permissions")?;
        }

        // Atomic rename
        fs::rename(&temp_path, &self.file_path)
            .context("Failed to rename temporary session file")?;

        log::info!(
            "Successfully saved session token to {}",
            self.file_path.display()
        );
        Ok(())
    }

    /// Deletes the session file.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` even if the file doesn't exist.
    pub fn delete(&self) -> Result<()> {
        if self.file_path.exists() {
            fs::remove_file(&self.file_path).context("Failed to delete session file")?;
            log::info!(
                "Successfully deleted session file at {}",
                self.file_path.display()
            );
        } else {
            log::debug!("Session file does not exist, nothing to delete");
        }
        Ok(())
    }

    /// Cleans up any old or stale session files.
    ///
    /// This ensures only ONE session file exists per user by removing:
    /// - Backup files (*.bak)
    /// - Temporary files (*.tmp)
    /// - Old session files with different extensions
    fn cleanup_old_files(&self) -> Result<()> {
        if let Some(parent) = self.file_path.parent() {
            if !parent.exists() {
                return Ok(());
            }

            let entries = fs::read_dir(parent).context("Failed to read .fido directory")?;

            for entry in entries {
                let entry = entry.context("Failed to read directory entry")?;
                let path = entry.path();

                // Skip if it's the current session file
                if path == self.file_path {
                    continue;
                }

                // Remove temporary files, backup files, and old session files
                if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
                    let is_stale_session_file = file_name == "session.tmp"
                        || file_name == "session.bak"
                        || file_name == "session.old"
                        || (file_name.starts_with("session_")
                            && (file_name.ends_with(".tmp")
                                || file_name.ends_with(".bak")
                                || file_name.ends_with(".old")));

                    if is_stale_session_file {
                        log::debug!("Removing old/stale session file: {}", path.display());
                        if let Err(e) = fs::remove_file(&path) {
                            log::warn!(
                                "Failed to remove old session file {}: {}",
                                path.display(),
                                e
                            );
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

fn server_scope_key(server_url: &str) -> String {
    let normalized = server_url.trim().trim_end_matches('/').to_ascii_lowercase();
    let mut hash = 0xcbf29ce484222325_u64;

    for byte in normalized.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }

    format!("{hash:016x}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_store(temp_dir: &TempDir) -> SessionStore {
        let file_path = temp_dir.path().join("session");
        SessionStore {
            file_path,
            legacy_file_path: None,
        }
    }

    #[test]
    fn test_save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        let token = "test-token-12345";
        store.save(token).unwrap();

        let loaded = store.load().unwrap();
        assert_eq!(loaded, Some(token.to_string()));
    }

    #[test]
    fn test_load_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        let loaded = store.load().unwrap();
        assert_eq!(loaded, None);
    }

    #[test]
    fn test_delete() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        let token = "test-token-12345";
        store.save(token).unwrap();
        assert!(store.file_path.exists());

        store.delete().unwrap();
        assert!(!store.file_path.exists());
    }

    #[test]
    fn test_delete_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        // Should not error even if file doesn't exist
        store.delete().unwrap();
    }

    #[test]
    fn test_empty_file_returns_none() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        // Create empty file
        fs::write(&store.file_path, "").unwrap();

        let loaded = store.load().unwrap();
        assert_eq!(loaded, None);
    }

    #[test]
    fn test_whitespace_only_returns_none() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        // Create file with only whitespace
        fs::write(&store.file_path, "   \n\t  ").unwrap();

        let loaded = store.load().unwrap();
        assert_eq!(loaded, None);
    }

    #[test]
    fn test_cleanup_old_files() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        // Create some old session files
        fs::write(temp_dir.path().join("session.bak"), "old-token").unwrap();
        fs::write(temp_dir.path().join("session.tmp"), "temp-token").unwrap();
        fs::write(temp_dir.path().join("session.old"), "old-token-2").unwrap();
        fs::write(temp_dir.path().join("session_deadbeef"), "other-server").unwrap();
        fs::write(
            temp_dir.path().join("session_deadbeef.json"),
            "old-instance-session",
        )
        .unwrap();

        // Save a new session (should clean up old files)
        store.save("new-token").unwrap();

        // Check that old files are removed
        assert!(!temp_dir.path().join("session.bak").exists());
        assert!(!temp_dir.path().join("session.tmp").exists());
        assert!(!temp_dir.path().join("session.old").exists());
        assert!(temp_dir.path().join("session_deadbeef").exists());
        assert!(temp_dir.path().join("session_deadbeef.json").exists());

        // Check that the new session file exists
        assert!(store.file_path.exists());
    }

    #[test]
    fn test_server_scoped_sessions_are_independent() {
        let temp_dir = TempDir::new().unwrap();
        let prod = SessionStore::for_server_in_test_dir(
            temp_dir.path().to_path_buf(),
            "https://fido.example.com",
        );
        let local = SessionStore::for_server_in_test_dir(
            temp_dir.path().to_path_buf(),
            "http://localhost:3000",
        );

        prod.save("prod-token").unwrap();
        local.save("local-token").unwrap();

        assert_eq!(prod.load().unwrap(), Some("prod-token".to_string()));
        assert_eq!(local.load().unwrap(), Some("local-token".to_string()));

        local.delete().unwrap();

        assert_eq!(prod.load().unwrap(), Some("prod-token".to_string()));
        assert_eq!(local.load().unwrap(), None);
    }

    #[test]
    fn test_legacy_session_migrates_to_server_scoped_file() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("session"), "legacy-token").unwrap();

        let store = SessionStore::for_server_in_test_dir(
            temp_dir.path().to_path_buf(),
            "https://fido.example.com/",
        );

        assert_eq!(store.load().unwrap(), Some("legacy-token".to_string()));
        assert!(store.file_path.exists());
        assert!(!temp_dir.path().join("session").exists());
        assert_eq!(
            fs::read_to_string(&store.file_path).unwrap(),
            "legacy-token"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_file_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        store.save("test-token").unwrap();

        let metadata = fs::metadata(&store.file_path).unwrap();
        let permissions = metadata.permissions();

        // Check that permissions are 0600
        assert_eq!(permissions.mode() & 0o777, 0o600);
    }

    #[test]
    fn test_invalid_token_length() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        // Token too short (less than 8 characters)
        fs::write(&store.file_path, "short").unwrap();
        assert_eq!(store.load().unwrap(), None);

        // Token too long (over 256 characters)
        let long_token = "a".repeat(300);
        fs::write(&store.file_path, long_token).unwrap();
        assert_eq!(store.load().unwrap(), None);
    }

    #[test]
    fn test_corrupted_file_with_control_chars() {
        let temp_dir = TempDir::new().unwrap();
        let store = create_test_store(&temp_dir);

        // Write binary data with control characters
        fs::write(&store.file_path, b"token\x00with\x01control\x02chars").unwrap();

        let loaded = store.load().unwrap();
        assert_eq!(loaded, None);
    }
}