zam 0.6.0

Enhanced shell history manager with sensitive data redaction
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Database-backed history management for zam
//!
//! This module provides SQLite-based history management with support for:
//! - Multi-host history tracking
//! - Session management
//! - Token extraction and storage
//! - Import from shell history files

use crate::config::Config;
use crate::database::{CommandEntry, Database, DatabaseStats};
use crate::error::{Error, Result};
use crate::redaction::RedactionEngine;
use chrono::{DateTime, Utc};
use regex::Regex;
use std::env;
use std::path::{Path, PathBuf};
use tracing::debug;

/// Database-backed history manager
pub struct HistoryManagerDb {
    config: Config,
    pub(crate) db: Database,
    redaction_engine: RedactionEngine,
}

/// Represents a redacted token extracted from a command
#[derive(Debug, Clone)]
pub struct ExtractedToken {
    pub token_type: String,
    pub placeholder: String,
    pub original_value: String,
}

impl HistoryManagerDb {
    /// Create a new database-backed history manager
    pub fn new(config: Config) -> Result<Self> {
        let redaction_engine = RedactionEngine::with_config(
            config.redaction.use_builtin_patterns,
            config.redaction.custom_patterns.clone(),
            config.redaction.exclude_patterns.clone(),
            config.redaction.placeholder.clone(),
            config.redaction.min_redaction_length,
            config.custom_env_vars.clone(),
            config.redaction.redact_env_vars,
        )?;

        // Get database path from config or default
        let db_path = config.history_file.with_extension("db");

        let db = Database::new(&db_path)?;

        Ok(Self {
            config,
            db,
            redaction_engine,
        })
    }

    /// Log a command to the database
    pub fn log_command(&mut self, command: &str) -> Result<()> {
        self.log_command_with_timestamp(command, None, None)
    }

    /// Log a command with a specific timestamp and exit code
    pub fn log_command_with_timestamp(
        &mut self,
        command: &str,
        timestamp: Option<DateTime<Utc>>,
        exit_code: Option<i32>,
    ) -> Result<()> {
        // Check if we should exclude this command
        if self.config.should_exclude_command(command) {
            return Ok(());
        }

        let timestamp = timestamp.unwrap_or_else(Utc::now);
        let directory = env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("<unknown>"))
            .to_string_lossy()
            .to_string();

        // Redact sensitive information and extract tokens
        let (redacted_command, tokens) = if self.config.enable_redaction {
            let (redacted, extracted) = self.redact_and_extract_tokens(command)?;
            let was_redacted = redacted != command;
            if was_redacted {
                debug!(
                    "Redacted sensitive data from command, extracted {} tokens",
                    extracted.len()
                );
            }
            (redacted, if was_redacted { extracted } else { vec![] })
        } else {
            (command.to_string(), vec![])
        };

        // Add command to database
        let command_id = self.db.add_command(
            &redacted_command,
            &directory,
            timestamp,
            !tokens.is_empty(),
            exit_code,
        )?;

        debug!("Logged command to database with ID {}", command_id);

        // Store extracted tokens
        for token in tokens {
            self.db.store_token(
                command_id,
                &token.token_type,
                &token.placeholder,
                &token.original_value,
            )?;
        }

        Ok(())
    }

    /// Redact a command and extract tokens for storage
    fn redact_and_extract_tokens(&self, command: &str) -> Result<(String, Vec<ExtractedToken>)> {
        let mut tokens = Vec::new();
        let mut redacted = command.to_string();

        // Define patterns for token extraction
        let patterns = vec![
            (
                r#"(?i)(?:password|passwd|pwd)[\s=:]+['"]?([^\s'"]{3,})['"]?"#,
                "password",
            ),
            (
                r#"(?i)(?:token|api_key|apikey|api-key)[\s=:]+['"]?([^\s'"]{10,})['"]?"#,
                "api_key",
            ),
            (
                r#"(?i)(?:secret|secret_key|secretkey)[\s=:]+['"]?([^\s'"]{10,})['"]?"#,
                "secret",
            ),
            (
                r#"(?i)(?:bearer|authorization)[\s:]+['"]?([^\s'"]{10,})['"]?"#,
                "bearer_token",
            ),
            (r#"(?i)--password[=\s]+['"]?([^\s'"]{3,})['"]?"#, "password"),
            (r#"(?i)-p\s+['"]?([^\s'"]{3,})['"]?"#, "password"),
        ];

        for (pattern_str, token_type) in patterns {
            let re = Regex::new(pattern_str)?;

            for caps in re.captures_iter(&redacted.clone()) {
                if let Some(matched) = caps.get(1) {
                    let original_value = matched.as_str().to_string();

                    // Skip if too short (likely not a real password)
                    if original_value.len() < self.config.redaction.min_redaction_length {
                        continue;
                    }

                    // Create placeholder
                    let placeholder = format!("<{}:{}>", token_type, tokens.len() + 1);

                    // Replace in redacted command
                    redacted = redacted.replace(&original_value, &placeholder);

                    tokens.push(ExtractedToken {
                        token_type: token_type.to_string(),
                        placeholder,
                        original_value,
                    });
                }
            }
        }

        // Also apply standard redaction engine
        if tokens.is_empty() {
            redacted = self.redaction_engine.redact(&redacted)?;
        }

        Ok((redacted, tokens))
    }

    /// Search commands in the database
    pub fn search(
        &self,
        query: &str,
        directory_filter: Option<&str>,
        host_filter: Option<&str>,
        limit: Option<usize>,
    ) -> Result<Vec<CommandEntry>> {
        self.db
            .search_commands(query, directory_filter, host_filter, limit)
    }

    /// Get recent commands
    pub fn get_recent(&self, limit: usize) -> Result<Vec<CommandEntry>> {
        self.db.get_recent_commands(limit)
    }

    /// Get all commands (for export)
    pub fn get_all_commands(&self) -> Result<Vec<CommandEntry>> {
        self.db.get_all_commands()
    }

    /// Get database statistics
    pub fn get_stats(&self) -> Result<DatabaseStats> {
        self.db.get_stats()
    }

    /// Get tokens for a specific command
    pub fn get_tokens_for_command(&self, command_id: i64) -> Result<Vec<crate::database::Token>> {
        self.db
            .get_tokens_for_command(crate::types::CommandId::new(command_id))
    }

    /// Get tokens by session ID
    pub fn get_tokens_by_session(&self, session_id: &str) -> Result<Vec<crate::database::Token>> {
        self.db.get_tokens_by_session(session_id)
    }

    /// Get tokens by directory
    pub fn get_tokens_by_directory(&self, directory: &str) -> Result<Vec<crate::database::Token>> {
        self.db.get_tokens_by_directory(directory)
    }

    /// Start a new session
    pub fn start_session(&mut self) -> Result<String> {
        self.db.start_session()
    }

    /// End a session
    pub fn end_session(&mut self, session_id: &str) -> Result<()> {
        self.db.end_session(session_id)
    }

    /// Import from bash history
    pub fn import_from_bash(&mut self, path: Option<PathBuf>) -> Result<usize> {
        let history_path = if let Some(p) = path {
            p
        } else {
            // Try to find bash history in default location
            let home = home::home_dir().ok_or(Error::HomeDirectoryNotFound)?;
            home.join(".bash_history")
        };

        if !history_path.exists() {
            return Err(Error::HistoryFileNotFound { path: history_path });
        }

        self.db.import_from_bash_history(&history_path)
    }

    /// Import from zsh history
    pub fn import_from_zsh(&mut self, path: Option<PathBuf>) -> Result<usize> {
        let history_path = if let Some(p) = path {
            p
        } else {
            // Try to find zsh history in default location
            let home = home::home_dir().ok_or(Error::HomeDirectoryNotFound)?;
            let zdotdir = env::var("ZDOTDIR").ok().map(PathBuf::from);
            let base_dir = zdotdir.unwrap_or(home);
            base_dir.join(".zsh_history")
        };

        if !history_path.exists() {
            return Err(Error::HistoryFileNotFound { path: history_path });
        }

        self.db.import_from_zsh_history(&history_path)
    }

    /// Import from fish history
    pub fn import_from_fish(&mut self, path: Option<PathBuf>) -> Result<usize> {
        let history_path = if let Some(p) = path {
            p
        } else {
            // Try to find fish history in default location
            let home = home::home_dir().ok_or(Error::HomeDirectoryNotFound)?;
            let config_dir = env::var("XDG_CONFIG_HOME")
                .ok()
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join(".config"));
            config_dir.join("fish").join("fish_history")
        };

        if !history_path.exists() {
            return Err(Error::HistoryFileNotFound { path: history_path });
        }

        // Fish history format is YAML-like, we'll do basic parsing
        let content = std::fs::read_to_string(&history_path)?;
        let mut imported_count = 0;

        let mut current_cmd: Option<String> = None;
        let mut current_time: Option<DateTime<Utc>> = None;

        for line in content.lines() {
            let line = line.trim();

            if line.starts_with("- cmd: ") {
                // Save previous command if exists
                if let (Some(cmd), Some(time)) = (current_cmd.take(), current_time.take()) {
                    self.db.add_command(&cmd, "<imported>", time, false, None)?;
                    imported_count += 1;
                }

                current_cmd = Some(line.trim_start_matches("- cmd: ").to_string());
            } else if line.starts_with("when: ")
                && let Ok(timestamp) = line.trim_start_matches("when: ").parse::<i64>()
                && let Some(dt) = DateTime::from_timestamp(timestamp, 0)
            {
                current_time = Some(dt);
            }
        }

        // Don't forget the last command
        if let (Some(cmd), Some(time)) = (current_cmd, current_time) {
            self.db.add_command(&cmd, "<imported>", time, false, None)?;
            imported_count += 1;
        }

        Ok(imported_count)
    }

    /// Merge from another database file
    pub fn merge_from_database(&mut self, other_db_path: &Path) -> Result<usize> {
        if !other_db_path.exists() {
            return Err(Error::HistoryFileNotFound {
                path: other_db_path.to_path_buf(),
            });
        }

        self.db.merge_from_database(other_db_path)
    }

    /// Get all hosts in the database
    pub fn get_hosts(&self) -> Result<Vec<crate::database::Host>> {
        self.db.get_hosts()
    }

    /// Get sessions for a host
    pub fn get_sessions_for_host(&self, host_id: i64) -> Result<Vec<crate::database::Session>> {
        self.db
            .get_sessions_for_host(crate::types::HostId::new(host_id))
    }

    /// Clear all data (use with caution!)
    pub fn clear(&self) -> Result<()> {
        self.db.clear()
    }
}

/// Implementation of HistoryProvider trait for database backend
impl crate::backend::HistoryProvider for HistoryManagerDb {
    fn get_entries(&self) -> Result<Vec<crate::history::HistoryEntry>> {
        Ok(self
            .get_all_commands()?
            .into_iter()
            .map(Into::into)
            .collect())
    }

    fn get_recent(&self, count: usize) -> Result<Vec<crate::history::HistoryEntry>> {
        Ok(self
            .get_recent(count)?
            .into_iter()
            .map(Into::into)
            .collect())
    }

    fn search(&self, query: &str) -> Result<Vec<crate::history::HistoryEntry>> {
        Ok(self
            .search(query, None, None, None)?
            .into_iter()
            .map(Into::into)
            .collect())
    }

    fn log_command(&mut self, command: &str) -> Result<()> {
        HistoryManagerDb::log_command(self, command)
    }

    fn clear(&mut self) -> Result<()> {
        self.db.clear()
    }

    fn delete_entries(&mut self, indices: &[usize]) -> Result<usize> {
        if indices.is_empty() {
            return Ok(0);
        }

        // Get all command IDs in order
        let entries = self.get_all_commands()?;

        // Collect command IDs to delete
        let mut ids_to_delete = Vec::new();
        for &idx in indices {
            if let Some(entry) = entries.get(idx) {
                ids_to_delete.push(entry.id);
            }
        }

        // Delete from database
        let mut deleted = 0;
        for id in ids_to_delete {
            self.db.delete_command(id)?;
            deleted += 1;
        }

        Ok(deleted)
    }
}

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

    fn test_config() -> (Config, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let temp_file = temp_dir.path().join("test.log");
        let mut config = Config {
            history_file: temp_file,
            enable_redaction: true,
            ..Default::default()
        };
        config.shell_integration.exclude_commands.clear();
        (config, temp_dir)
    }

    #[test]
    fn test_history_manager_creation() {
        let (config, _temp_dir) = test_config();
        let manager = HistoryManagerDb::new(config);
        assert!(manager.is_ok());
    }

    #[test]
    fn test_log_command() {
        let (config, _temp_dir) = test_config();
        let mut manager = HistoryManagerDb::new(config).unwrap();

        let result = manager.log_command("ls -la");
        assert!(result.is_ok());

        let stats = manager.get_stats().unwrap();
        assert_eq!(stats.total_commands, 1);
    }

    #[test]
    fn test_redaction_with_tokens() {
        let (config, _temp_dir) = test_config();
        let mut manager = HistoryManagerDb::new(config).unwrap();

        manager
            .log_command("mysql -u root -p secret123 -h localhost")
            .unwrap();

        let commands = manager.get_recent(10).unwrap();
        assert_eq!(commands.len(), 1);
        assert!(commands[0].redacted);
        assert!(!commands[0].command.contains("secret123"));
    }

    #[test]
    fn test_token_extraction() {
        let (config, _temp_dir) = test_config();
        let manager = HistoryManagerDb::new(config).unwrap();

        let (redacted, tokens) = manager
            .redact_and_extract_tokens("export API_KEY=abc123xyz456")
            .unwrap();

        assert!(!tokens.is_empty());
        assert!(!redacted.contains("abc123xyz456"));
    }

    #[test]
    fn test_search() {
        let (config, _temp_dir) = test_config();
        let mut manager = HistoryManagerDb::new(config).unwrap();

        manager.log_command("git status").unwrap();
        manager.log_command("git commit -m 'test'").unwrap();
        manager.log_command("ls -la").unwrap();

        let results = manager.search("git", None, None, None).unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_token_retrieval() {
        let (config, _temp_dir) = test_config();
        let mut manager = HistoryManagerDb::new(config).unwrap();

        manager.log_command("export PASSWORD=mypass123").unwrap();

        let commands = manager.get_recent(1).unwrap();
        let tokens = manager
            .get_tokens_for_command(commands[0].id.as_i64())
            .unwrap();

        assert!(!tokens.is_empty());
    }
}