lazy-locker 0.0.3

A secure local secrets manager with TUI interface and SDK support
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Secure process execution module with secret injection.
//!
//! This module provides a secure wrapper for executing scripts
//! with decrypted tokens injected in memory, without ever writing
//! plain text values to disk.

use std::path::PathBuf;
use std::process::{Command, Stdio};
use anyhow::Result;
use zeroize::Zeroize;

use crate::core::store::SecretsStore;

/// Result of a file search for files using a token
#[derive(Debug, Clone)]
pub struct TokenUsage {
    pub file_path: String,
    pub line_number: usize,
    pub line_content: String,
}

/// Searches for files in the current directory that reference a token
pub fn find_token_usages(token_name: &str, search_dir: &PathBuf) -> Vec<TokenUsage> {
    let mut usages = Vec::new();
    
    // Patterns to search for
    let patterns = vec![
        format!("${{{}}}", token_name),           // ${TOKEN_NAME}
        format!("${}",  token_name),              // $TOKEN_NAME
        format!("process.env.{}", token_name),    // process.env.TOKEN_NAME
        format!("os.environ[\"{}\"]", token_name), // os.environ["TOKEN_NAME"]
        format!("os.getenv(\"{}\")", token_name), // os.getenv("TOKEN_NAME")
        format!("ENV[\"{}\"]", token_name),       // ENV["TOKEN_NAME"]
        token_name.to_string(),                   // Direct reference
    ];
    
    if let Ok(entries) = walkdir(search_dir) {
        for entry in entries {
            if let Ok(content) = std::fs::read_to_string(&entry) {
                for (line_num, line) in content.lines().enumerate() {
                    for pattern in &patterns {
                        if line.contains(pattern) {
                            usages.push(TokenUsage {
                                file_path: entry.to_string_lossy().to_string(),
                                line_number: line_num + 1,
                                line_content: line.trim().to_string(),
                            });
                            break; // One occurrence per line only
                        }
                    }
                }
            }
        }
    }
    
    usages
}

/// Recursively walks a directory ignoring hidden folders and node_modules
fn walkdir(dir: &PathBuf) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    
    if !dir.is_dir() {
        return Ok(files);
    }
    
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        let name = path.file_name().unwrap_or_default().to_string_lossy();
        
        // Ignore hidden folders, node_modules, target, .git, etc.
        if name.starts_with('.') || name == "node_modules" || name == "target" || name == "__pycache__" {
            continue;
        }
        
        if path.is_dir() {
            files.extend(walkdir(&path)?);
        } else {
            // Filter by extension
            let ext = path.extension().unwrap_or_default().to_string_lossy();
            if matches!(ext.as_ref(), "py" | "js" | "ts" | "jsx" | "tsx" | "sh" | "bash" | "env" | "yaml" | "yml" | "json" | "toml" | "rb" | "go" | "rs") {
                files.push(path);
            }
        }
    }
    
    Ok(files)
}

/// Executes a command with secrets injected as environment variables.
/// Secrets are decrypted in memory and zeroized after execution.
pub fn execute_with_secrets(
    command: &str,
    store: &SecretsStore,
    key: &[u8],
) -> Result<std::process::Output> {
    // Decrypt all secrets in memory
    let mut env_vars = store.decrypt_all(key)?;
    
    // Execute the command with environment variables
    let output = Command::new("sh")
        .arg("-c")
        .arg(command)
        .envs(&env_vars)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()?;
    
    // Zeroize secrets after use
    for (_, mut value) in env_vars.drain() {
        value.zeroize();
    }
    
    Ok(output)
}

/// Generates a Python wrapper script that uses lazy-locker to inject secrets.
/// This wrapper calls lazy-locker in subprocess to decrypt on the fly.
pub fn generate_python_wrapper(script_path: &str, locker_path: &PathBuf) -> String {
    format!(r#"#!/usr/bin/env python3
"""
Secure wrapper generated by lazy-locker.
This script injects secrets in memory before executing the target script.
"""
import subprocess
import sys
import os

def main():
    # Call lazy-locker to get secrets (via secure pipe)
    result = subprocess.run(
        ['lazy-locker', 'export', '--format', 'env'],
        capture_output=True,
        text=True,
        cwd='{locker_dir}'
    )
    
    if result.returncode != 0:
        print("Error: Unable to load secrets", file=sys.stderr)
        sys.exit(1)
    
    # Parse environment variables
    env = os.environ.copy()
    for line in result.stdout.strip().split('\n'):
        if '=' in line:
            key, value = line.split('=', 1)
            env[key] = value
    
    # Execute target script with injected secrets
    subprocess.run([sys.executable, '{script}'] + sys.argv[1:], env=env)

if __name__ == '__main__':
    main()
"#, 
        locker_dir = locker_path.display(),
        script = script_path
    )
}

/// Generates a .env.encrypted file with token references.
/// This file can be versioned as it only contains names, not values.
pub fn generate_env_reference(store: &SecretsStore, output_path: &PathBuf) -> Result<()> {
    let mut content = String::from("# File generated by lazy-locker\n");
    content.push_str("# Values are stored securely in the locker.\n");
    content.push_str("# Use 'lazy-locker run <command>' to execute with secrets.\n\n");
    
    for secret in store.list_secrets() {
        let expiration = secret.expiration_display();
        content.push_str(&format!("# {} - {}\n", secret.name, expiration));
        content.push_str(&format!("{}=${{LAZY_LOCKER:{}}}\n\n", secret.name, secret.name));
    }
    
    std::fs::write(output_path, content)?;
    Ok(())
}

/// Exports secrets in .env compatible format (for temporary use only).
/// WARNING: This function writes secrets in plain text. Use with caution.
pub fn export_env_format(store: &SecretsStore, key: &[u8]) -> Result<String> {
    let secrets = store.decrypt_all(key)?;
    let mut output = String::new();
    
    for (name, mut value) in secrets {
        // Escape special characters
        let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");
        output.push_str(&format!("{}=\"{}\"\n", name, escaped_value));
        value.zeroize();
    }
    
    Ok(output)
}

/// Copies a value to clipboard (cross-platform).
pub fn copy_to_clipboard(value: &str) -> Result<()> {
    #[cfg(target_os = "linux")]
    {
        // Try xclip then xsel
        let result = Command::new("xclip")
            .args(["-selection", "clipboard"])
            .stdin(Stdio::piped())
            .spawn()
            .and_then(|mut child| {
                use std::io::Write;
                if let Some(ref mut stdin) = child.stdin {
                    stdin.write_all(value.as_bytes())?;
                }
                child.wait()
            });
        
        if result.is_ok() {
            return Ok(());
        }
        
        // Fallback to xsel
        let result = Command::new("xsel")
            .args(["--clipboard", "--input"])
            .stdin(Stdio::piped())
            .spawn()
            .and_then(|mut child| {
                use std::io::Write;
                if let Some(ref mut stdin) = child.stdin {
                    stdin.write_all(value.as_bytes())?;
                }
                child.wait()
            });
        
        if result.is_ok() {
            return Ok(());
        }
        
        // Try wl-copy for Wayland
        let result = Command::new("wl-copy")
            .stdin(Stdio::piped())
            .spawn()
            .and_then(|mut child| {
                use std::io::Write;
                if let Some(ref mut stdin) = child.stdin {
                    stdin.write_all(value.as_bytes())?;
                }
                child.wait()
            });
        
        result.map_err(|_| anyhow::anyhow!("No clipboard tool available (xclip, xsel, wl-copy)"))?;
    }
    
    #[cfg(target_os = "macos")]
    {
        Command::new("pbcopy")
            .stdin(Stdio::piped())
            .spawn()
            .and_then(|mut child| {
                use std::io::Write;
                if let Some(ref mut stdin) = child.stdin {
                    stdin.write_all(value.as_bytes())?;
                }
                child.wait()
            })
            .map_err(|e| anyhow::anyhow!("pbcopy error: {}", e))?;
    }
    
    #[cfg(target_os = "windows")]
    {
        Command::new("clip")
            .stdin(Stdio::piped())
            .spawn()
            .and_then(|mut child| {
                use std::io::Write;
                if let Some(ref mut stdin) = child.stdin {
                    stdin.write_all(value.as_bytes())?;
                }
                child.wait()
            })
            .map_err(|e| anyhow::anyhow!("clip error: {}", e))?;
    }
    
    Ok(())
}

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

    // ========================
    // walkdir tests
    // ========================

    #[test]
    fn test_walkdir_finds_supported_files() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        // Create test files
        fs::write(temp_dir.path().join("script.py"), "print('hello')").unwrap();
        fs::write(temp_dir.path().join("app.js"), "console.log('hi')").unwrap();
        fs::write(temp_dir.path().join("config.json"), "{}").unwrap();
        fs::write(temp_dir.path().join("readme.txt"), "ignored").unwrap();
        
        let files = walkdir(&temp_dir.path().to_path_buf()).expect("walkdir failed");
        
        assert_eq!(files.len(), 3); // .py, .js, .json - not .txt
    }

    #[test]
    fn test_walkdir_ignores_hidden_dirs() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        // Create hidden directory with file
        let hidden_dir = temp_dir.path().join(".hidden");
        fs::create_dir(&hidden_dir).unwrap();
        fs::write(hidden_dir.join("secret.py"), "hidden").unwrap();
        
        // Create visible file
        fs::write(temp_dir.path().join("visible.py"), "visible").unwrap();
        
        let files = walkdir(&temp_dir.path().to_path_buf()).expect("walkdir failed");
        
        assert_eq!(files.len(), 1);
        assert!(files[0].to_string_lossy().contains("visible.py"));
    }

    #[test]
    fn test_walkdir_ignores_node_modules() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        // Create node_modules directory
        let node_modules = temp_dir.path().join("node_modules");
        fs::create_dir(&node_modules).unwrap();
        fs::write(node_modules.join("dep.js"), "dependency").unwrap();
        
        // Create source file
        fs::write(temp_dir.path().join("index.js"), "main").unwrap();
        
        let files = walkdir(&temp_dir.path().to_path_buf()).expect("walkdir failed");
        
        assert_eq!(files.len(), 1);
        assert!(files[0].to_string_lossy().contains("index.js"));
    }

    #[test]
    fn test_walkdir_recursive() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        // Create nested structure
        let src = temp_dir.path().join("src");
        let deep = src.join("deep").join("nested");
        fs::create_dir_all(&deep).unwrap();
        
        fs::write(temp_dir.path().join("root.py"), "root").unwrap();
        fs::write(src.join("module.py"), "module").unwrap();
        fs::write(deep.join("helper.py"), "helper").unwrap();
        
        let files = walkdir(&temp_dir.path().to_path_buf()).expect("walkdir failed");
        
        assert_eq!(files.len(), 3);
    }

    #[test]
    fn test_walkdir_empty_directory() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        let files = walkdir(&temp_dir.path().to_path_buf()).expect("walkdir failed");
        
        assert!(files.is_empty());
    }

    #[test]
    fn test_walkdir_nonexistent_directory() {
        let nonexistent = PathBuf::from("/nonexistent/path/12345");
        
        let files = walkdir(&nonexistent).expect("walkdir should not fail");
        
        assert!(files.is_empty());
    }

    // ========================
    // find_token_usages tests
    // ========================

    #[test]
    fn test_find_token_usages_env_variable_syntax() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        // Create files with various token reference patterns
        fs::write(
            temp_dir.path().join("script.sh"),
            "echo $MY_API_KEY\necho ${MY_API_KEY}"
        ).unwrap();
        
        let usages = find_token_usages("MY_API_KEY", &temp_dir.path().to_path_buf());
        
        assert!(!usages.is_empty());
        assert!(usages.iter().any(|u| u.line_content.contains("$MY_API_KEY")));
    }

    #[test]
    fn test_find_token_usages_python_syntax() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        fs::write(
            temp_dir.path().join("app.py"),
            r#"import os
api_key = os.environ["DB_PASSWORD"]
other = os.getenv("DB_PASSWORD")
"#
        ).unwrap();
        
        let usages = find_token_usages("DB_PASSWORD", &temp_dir.path().to_path_buf());
        
        assert!(usages.len() >= 2);
    }

    #[test]
    fn test_find_token_usages_javascript_syntax() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        fs::write(
            temp_dir.path().join("server.js"),
            "const key = process.env.SECRET_KEY;"
        ).unwrap();
        
        let usages = find_token_usages("SECRET_KEY", &temp_dir.path().to_path_buf());
        
        assert_eq!(usages.len(), 1);
        assert!(usages[0].line_content.contains("process.env.SECRET_KEY"));
    }

    #[test]
    fn test_find_token_usages_no_matches() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        fs::write(
            temp_dir.path().join("clean.py"),
            "print('no secrets here')"
        ).unwrap();
        
        let usages = find_token_usages("NONEXISTENT_TOKEN", &temp_dir.path().to_path_buf());
        
        assert!(usages.is_empty());
    }

    #[test]
    fn test_find_token_usages_includes_line_info() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        
        fs::write(
            temp_dir.path().join("config.py"),
            "# Comment\nTOKEN = $API_KEY\n# End"
        ).unwrap();
        
        let usages = find_token_usages("API_KEY", &temp_dir.path().to_path_buf());
        
        assert_eq!(usages.len(), 1);
        assert_eq!(usages[0].line_number, 2);
        assert!(usages[0].file_path.contains("config.py"));
    }

    // ========================
    // generate_env_reference tests
    // ========================

    #[test]
    fn test_generate_env_reference_creates_file() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let key = [0x42u8; 32];
        let mut store = crate::core::store::SecretsStore::new();
        
        store.add_secret(
            "TEST_VAR".to_string(),
            "value".to_string(),
            None,
            &temp_dir.path().to_path_buf(),
            &key,
        ).expect("Failed to add secret");
        
        let output_path = temp_dir.path().join(".env.encrypted");
        generate_env_reference(&store, &output_path).expect("Failed to generate reference");
        
        assert!(output_path.exists());
        
        let content = fs::read_to_string(&output_path).unwrap();
        assert!(content.contains("TEST_VAR"));
        assert!(content.contains("LAZY_LOCKER:TEST_VAR"));
        assert!(content.contains("# File generated by lazy-locker"));
    }

    #[test]
    fn test_generate_env_reference_no_plaintext_values() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let key = [0x42u8; 32];
        let mut store = crate::core::store::SecretsStore::new();
        
        let secret_value = "super_secret_password_123";
        store.add_secret(
            "PASSWORD".to_string(),
            secret_value.to_string(),
            None,
            &temp_dir.path().to_path_buf(),
            &key,
        ).expect("Failed to add secret");
        
        let output_path = temp_dir.path().join(".env.ref");
        generate_env_reference(&store, &output_path).expect("Failed to generate reference");
        
        let content = fs::read_to_string(&output_path).unwrap();
        
        // The actual secret value should NOT appear in the reference file
        assert!(!content.contains(secret_value));
        // Only the placeholder should appear
        assert!(content.contains("${LAZY_LOCKER:PASSWORD}"));
    }

    // ========================
    // generate_python_wrapper tests
    // ========================

    #[test]
    fn test_generate_python_wrapper_structure() {
        let locker_path = PathBuf::from("/home/user/.lazy-locker");
        let wrapper = generate_python_wrapper("app.py", &locker_path);
        
        assert!(wrapper.contains("#!/usr/bin/env python3"));
        assert!(wrapper.contains("lazy-locker"));
        assert!(wrapper.contains("app.py"));
        assert!(wrapper.contains("/home/user/.lazy-locker"));
        assert!(wrapper.contains("def main()"));
    }

    // ========================
    // TokenUsage struct tests
    // ========================

    #[test]
    fn test_token_usage_clone() {
        let usage = TokenUsage {
            file_path: "src/main.py".to_string(),
            line_number: 42,
            line_content: "api_key = os.environ['KEY']".to_string(),
        };

        let cloned = usage.clone();
        
        assert_eq!(cloned.file_path, usage.file_path);
        assert_eq!(cloned.line_number, usage.line_number);
        assert_eq!(cloned.line_content, usage.line_content);
    }
}