lazy-locker 0.0.7

A secure local secrets manager with TUI interface and SDK support
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
//! 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 anyhow::Result;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use zeroize::Zeroize;

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

/// 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.
#[allow(dead_code)]
pub fn generate_python_wrapper(script_path: &str, locker_path: &std::path::Path) -> 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.
#[allow(dead_code)]
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.
#[allow(dead_code)]
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(())
}

/// Marker comment used to identify lazy-locker exports in shell profiles
const SHELL_MARKER_START: &str = "# >>> lazy-locker exports >>>";
const SHELL_MARKER_END: &str = "# <<< lazy-locker exports <<<";

/// Generates a .env file with secrets in plain text.
/// WARNING: This writes secrets in plain text to disk.
pub fn generate_env_file(
    store: &SecretsStore,
    key: &[u8],
    output_path: &std::path::PathBuf,
) -> Result<()> {
    let secrets = store.decrypt_all(key)?;
    let mut content = String::from("# Generated by lazy-locker\n");
    content.push_str("# WARNING: This file contains secrets in plain text!\n");
    content.push_str("# Do not commit this file to version control.\n\n");

    for (name, mut value) in secrets {
        let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");
        content.push_str(&format!("{}=\"{}\"\n", name, escaped_value));
        value.zeroize();
    }

    std::fs::write(output_path, content)?;
    Ok(())
}

/// Exports secrets to a shell profile file (bash, zsh, fish).
/// Adds export statements within markers for easy removal.
pub fn export_to_shell_profile(
    store: &SecretsStore,
    key: &[u8],
    shell: &str,
) -> Result<std::path::PathBuf> {
    let home =
        std::env::var("HOME").map_err(|_| anyhow::anyhow!("HOME environment variable not set"))?;

    let profile_path = match shell {
        "bash" => std::path::PathBuf::from(&home).join(".bashrc"),
        "zsh" => std::path::PathBuf::from(&home).join(".zshrc"),
        "fish" => std::path::PathBuf::from(&home).join(".config/fish/config.fish"),
        _ => return Err(anyhow::anyhow!("Unsupported shell: {}", shell)),
    };

    // Generate export lines
    let secrets = store.decrypt_all(key)?;
    let mut exports = String::new();
    exports.push_str(&format!("\n{}\n", SHELL_MARKER_START));
    exports.push_str("# WARNING: Secrets in plain text - generated by lazy-locker\n");

    for (name, mut value) in secrets {
        let escaped_value = value
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('$', "\\$");
        if shell == "fish" {
            exports.push_str(&format!("set -gx {} \"{}\"\n", name, escaped_value));
        } else {
            exports.push_str(&format!("export {}=\"{}\"\n", name, escaped_value));
        }
        value.zeroize();
    }

    exports.push_str(&format!("{}\n", SHELL_MARKER_END));

    // Read existing content
    let existing = std::fs::read_to_string(&profile_path).unwrap_or_default();

    // Remove old lazy-locker exports if present
    let cleaned = remove_shell_exports_from_content(&existing);

    // Append new exports
    let new_content = format!("{}{}", cleaned.trim_end(), exports);

    // Ensure parent directory exists (for fish)
    if let Some(parent) = profile_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    std::fs::write(&profile_path, new_content)?;

    Ok(profile_path)
}

/// Removes lazy-locker exports from shell profile content.
fn remove_shell_exports_from_content(content: &str) -> String {
    let mut result = String::new();
    let mut in_marker = false;

    for line in content.lines() {
        if line.trim() == SHELL_MARKER_START {
            in_marker = true;
            continue;
        }
        if line.trim() == SHELL_MARKER_END {
            in_marker = false;
            continue;
        }
        if !in_marker {
            result.push_str(line);
            result.push('\n');
        }
    }

    result
}

/// Clears lazy-locker exports from all known shell profiles.
pub fn clear_shell_exports() -> Result<Vec<std::path::PathBuf>> {
    let home =
        std::env::var("HOME").map_err(|_| anyhow::anyhow!("HOME environment variable not set"))?;

    let profiles = [
        std::path::PathBuf::from(&home).join(".bashrc"),
        std::path::PathBuf::from(&home).join(".zshrc"),
        std::path::PathBuf::from(&home).join(".config/fish/config.fish"),
    ];

    let mut cleared = Vec::new();

    for profile_path in profiles {
        if profile_path.exists() {
            let content = std::fs::read_to_string(&profile_path)?;
            if content.contains(SHELL_MARKER_START) {
                let cleaned = remove_shell_exports_from_content(&content);
                std::fs::write(&profile_path, cleaned)?;
                cleared.push(profile_path);
            }
        }
    }

    Ok(cleared)
}

/// Exports secrets as a JSON file.
pub fn export_to_json(
    store: &SecretsStore,
    key: &[u8],
    output_path: &std::path::PathBuf,
) -> Result<()> {
    let secrets = store.decrypt_all(key)?;
    let json = serde_json::to_string_pretty(&secrets)?;
    std::fs::write(output_path, json)?;
    Ok(())
}

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

    // ========================
    // 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(),
                &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(),
                &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()"));
    }
}