1use anyhow::Result;
8use std::path::PathBuf;
9use std::process::{Command, Stdio};
10use zeroize::Zeroize;
11
12use crate::core::store::SecretsStore;
13
14pub fn execute_with_secrets(
17 command: &str,
18 store: &SecretsStore,
19 key: &[u8],
20) -> Result<std::process::Output> {
21 let mut env_vars = store.decrypt_all(key)?;
23
24 let output = Command::new("sh")
26 .arg("-c")
27 .arg(command)
28 .envs(&env_vars)
29 .stdout(Stdio::piped())
30 .stderr(Stdio::piped())
31 .output()?;
32
33 for (_, mut value) in env_vars.drain() {
35 value.zeroize();
36 }
37
38 Ok(output)
39}
40
41#[allow(dead_code)]
44pub fn generate_python_wrapper(script_path: &str, locker_path: &std::path::Path) -> String {
45 format!(
46 r#"#!/usr/bin/env python3
47"""
48Secure wrapper generated by lazy-locker.
49This script injects secrets in memory before executing the target script.
50"""
51import subprocess
52import sys
53import os
54
55def main():
56 # Call lazy-locker to get secrets (via secure pipe)
57 result = subprocess.run(
58 ['lazy-locker', 'export', '--format', 'env'],
59 capture_output=True,
60 text=True,
61 cwd='{locker_dir}'
62 )
63
64 if result.returncode != 0:
65 print("Error: Unable to load secrets", file=sys.stderr)
66 sys.exit(1)
67
68 # Parse environment variables
69 env = os.environ.copy()
70 for line in result.stdout.strip().split('\n'):
71 if '=' in line:
72 key, value = line.split('=', 1)
73 env[key] = value
74
75 # Execute target script with injected secrets
76 subprocess.run([sys.executable, '{script}'] + sys.argv[1:], env=env)
77
78if __name__ == '__main__':
79 main()
80"#,
81 locker_dir = locker_path.display(),
82 script = script_path
83 )
84}
85
86#[allow(dead_code)]
89pub fn generate_env_reference(store: &SecretsStore, output_path: &PathBuf) -> Result<()> {
90 let mut content = String::from("# File generated by lazy-locker\n");
91 content.push_str("# Values are stored securely in the locker.\n");
92 content.push_str("# Use 'lazy-locker run <command>' to execute with secrets.\n\n");
93
94 for secret in store.list_secrets() {
95 let expiration = secret.expiration_display();
96 content.push_str(&format!("# {} - {}\n", secret.name, expiration));
97 content.push_str(&format!(
98 "{}=${{LAZY_LOCKER:{}}}\n\n",
99 secret.name, secret.name
100 ));
101 }
102
103 std::fs::write(output_path, content)?;
104 Ok(())
105}
106
107#[allow(dead_code)]
110pub fn export_env_format(store: &SecretsStore, key: &[u8]) -> Result<String> {
111 let secrets = store.decrypt_all(key)?;
112 let mut output = String::new();
113
114 for (name, mut value) in secrets {
115 let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");
117 output.push_str(&format!("{}=\"{}\"\n", name, escaped_value));
118 value.zeroize();
119 }
120
121 Ok(output)
122}
123
124pub fn copy_to_clipboard(value: &str) -> Result<()> {
126 #[cfg(target_os = "linux")]
127 {
128 let result = Command::new("xclip")
130 .args(["-selection", "clipboard"])
131 .stdin(Stdio::piped())
132 .spawn()
133 .and_then(|mut child| {
134 use std::io::Write;
135 if let Some(ref mut stdin) = child.stdin {
136 stdin.write_all(value.as_bytes())?;
137 }
138 child.wait()
139 });
140
141 if result.is_ok() {
142 return Ok(());
143 }
144
145 let result = Command::new("xsel")
147 .args(["--clipboard", "--input"])
148 .stdin(Stdio::piped())
149 .spawn()
150 .and_then(|mut child| {
151 use std::io::Write;
152 if let Some(ref mut stdin) = child.stdin {
153 stdin.write_all(value.as_bytes())?;
154 }
155 child.wait()
156 });
157
158 if result.is_ok() {
159 return Ok(());
160 }
161
162 let result = Command::new("wl-copy")
164 .stdin(Stdio::piped())
165 .spawn()
166 .and_then(|mut child| {
167 use std::io::Write;
168 if let Some(ref mut stdin) = child.stdin {
169 stdin.write_all(value.as_bytes())?;
170 }
171 child.wait()
172 });
173
174 result
175 .map_err(|_| anyhow::anyhow!("No clipboard tool available (xclip, xsel, wl-copy)"))?;
176 }
177
178 #[cfg(target_os = "macos")]
179 {
180 Command::new("pbcopy")
181 .stdin(Stdio::piped())
182 .spawn()
183 .and_then(|mut child| {
184 use std::io::Write;
185 if let Some(ref mut stdin) = child.stdin {
186 stdin.write_all(value.as_bytes())?;
187 }
188 child.wait()
189 })
190 .map_err(|e| anyhow::anyhow!("pbcopy error: {}", e))?;
191 }
192
193 #[cfg(target_os = "windows")]
194 {
195 Command::new("clip")
196 .stdin(Stdio::piped())
197 .spawn()
198 .and_then(|mut child| {
199 use std::io::Write;
200 if let Some(ref mut stdin) = child.stdin {
201 stdin.write_all(value.as_bytes())?;
202 }
203 child.wait()
204 })
205 .map_err(|e| anyhow::anyhow!("clip error: {}", e))?;
206 }
207
208 Ok(())
209}
210
211const SHELL_MARKER_START: &str = "# >>> lazy-locker exports >>>";
213const SHELL_MARKER_END: &str = "# <<< lazy-locker exports <<<";
214
215pub fn generate_env_file(
218 store: &SecretsStore,
219 key: &[u8],
220 output_path: &std::path::PathBuf,
221) -> Result<()> {
222 let secrets = store.decrypt_all(key)?;
223 let mut content = String::from("# Generated by lazy-locker\n");
224 content.push_str("# WARNING: This file contains secrets in plain text!\n");
225 content.push_str("# Do not commit this file to version control.\n\n");
226
227 for (name, mut value) in secrets {
228 let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");
229 content.push_str(&format!("{}=\"{}\"\n", name, escaped_value));
230 value.zeroize();
231 }
232
233 std::fs::write(output_path, content)?;
234 Ok(())
235}
236
237pub fn export_to_shell_profile(
240 store: &SecretsStore,
241 key: &[u8],
242 shell: &str,
243) -> Result<std::path::PathBuf> {
244 let home =
245 std::env::var("HOME").map_err(|_| anyhow::anyhow!("HOME environment variable not set"))?;
246
247 let profile_path = match shell {
248 "bash" => std::path::PathBuf::from(&home).join(".bashrc"),
249 "zsh" => std::path::PathBuf::from(&home).join(".zshrc"),
250 "fish" => std::path::PathBuf::from(&home).join(".config/fish/config.fish"),
251 _ => return Err(anyhow::anyhow!("Unsupported shell: {}", shell)),
252 };
253
254 let secrets = store.decrypt_all(key)?;
256 let mut exports = String::new();
257 exports.push_str(&format!("\n{}\n", SHELL_MARKER_START));
258 exports.push_str("# WARNING: Secrets in plain text - generated by lazy-locker\n");
259
260 for (name, mut value) in secrets {
261 let escaped_value = value
262 .replace('\\', "\\\\")
263 .replace('"', "\\\"")
264 .replace('$', "\\$");
265 if shell == "fish" {
266 exports.push_str(&format!("set -gx {} \"{}\"\n", name, escaped_value));
267 } else {
268 exports.push_str(&format!("export {}=\"{}\"\n", name, escaped_value));
269 }
270 value.zeroize();
271 }
272
273 exports.push_str(&format!("{}\n", SHELL_MARKER_END));
274
275 let existing = std::fs::read_to_string(&profile_path).unwrap_or_default();
277
278 let cleaned = remove_shell_exports_from_content(&existing);
280
281 let new_content = format!("{}{}", cleaned.trim_end(), exports);
283
284 if let Some(parent) = profile_path.parent() {
286 std::fs::create_dir_all(parent)?;
287 }
288
289 std::fs::write(&profile_path, new_content)?;
290
291 Ok(profile_path)
292}
293
294fn remove_shell_exports_from_content(content: &str) -> String {
296 let mut result = String::new();
297 let mut in_marker = false;
298
299 for line in content.lines() {
300 if line.trim() == SHELL_MARKER_START {
301 in_marker = true;
302 continue;
303 }
304 if line.trim() == SHELL_MARKER_END {
305 in_marker = false;
306 continue;
307 }
308 if !in_marker {
309 result.push_str(line);
310 result.push('\n');
311 }
312 }
313
314 result
315}
316
317pub fn clear_shell_exports() -> Result<Vec<std::path::PathBuf>> {
319 let home =
320 std::env::var("HOME").map_err(|_| anyhow::anyhow!("HOME environment variable not set"))?;
321
322 let profiles = [
323 std::path::PathBuf::from(&home).join(".bashrc"),
324 std::path::PathBuf::from(&home).join(".zshrc"),
325 std::path::PathBuf::from(&home).join(".config/fish/config.fish"),
326 ];
327
328 let mut cleared = Vec::new();
329
330 for profile_path in profiles {
331 if profile_path.exists() {
332 let content = std::fs::read_to_string(&profile_path)?;
333 if content.contains(SHELL_MARKER_START) {
334 let cleaned = remove_shell_exports_from_content(&content);
335 std::fs::write(&profile_path, cleaned)?;
336 cleared.push(profile_path);
337 }
338 }
339 }
340
341 Ok(cleared)
342}
343
344pub fn export_to_json(
346 store: &SecretsStore,
347 key: &[u8],
348 output_path: &std::path::PathBuf,
349) -> Result<()> {
350 let secrets = store.decrypt_all(key)?;
351 let json = serde_json::to_string_pretty(&secrets)?;
352 std::fs::write(output_path, json)?;
353 Ok(())
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359 use std::fs;
360 use tempfile::TempDir;
361
362 #[test]
367 fn test_generate_env_reference_creates_file() {
368 let temp_dir = TempDir::new().expect("Failed to create temp dir");
369 let key = [0x42u8; 32];
370 let mut store = crate::core::store::SecretsStore::new();
371
372 store
373 .add_secret(
374 "TEST_VAR".to_string(),
375 "value".to_string(),
376 None,
377 temp_dir.path(),
378 &key,
379 )
380 .expect("Failed to add secret");
381
382 let output_path = temp_dir.path().join(".env.encrypted");
383 generate_env_reference(&store, &output_path).expect("Failed to generate reference");
384
385 assert!(output_path.exists());
386
387 let content = fs::read_to_string(&output_path).unwrap();
388 assert!(content.contains("TEST_VAR"));
389 assert!(content.contains("LAZY_LOCKER:TEST_VAR"));
390 assert!(content.contains("# File generated by lazy-locker"));
391 }
392
393 #[test]
394 fn test_generate_env_reference_no_plaintext_values() {
395 let temp_dir = TempDir::new().expect("Failed to create temp dir");
396 let key = [0x42u8; 32];
397 let mut store = crate::core::store::SecretsStore::new();
398
399 let secret_value = "super_secret_password_123";
400 store
401 .add_secret(
402 "PASSWORD".to_string(),
403 secret_value.to_string(),
404 None,
405 temp_dir.path(),
406 &key,
407 )
408 .expect("Failed to add secret");
409
410 let output_path = temp_dir.path().join(".env.ref");
411 generate_env_reference(&store, &output_path).expect("Failed to generate reference");
412
413 let content = fs::read_to_string(&output_path).unwrap();
414
415 assert!(!content.contains(secret_value));
417 assert!(content.contains("${LAZY_LOCKER:PASSWORD}"));
419 }
420
421 #[test]
426 fn test_generate_python_wrapper_structure() {
427 let locker_path = PathBuf::from("/home/user/.lazy-locker");
428 let wrapper = generate_python_wrapper("app.py", &locker_path);
429
430 assert!(wrapper.contains("#!/usr/bin/env python3"));
431 assert!(wrapper.contains("lazy-locker"));
432 assert!(wrapper.contains("app.py"));
433 assert!(wrapper.contains("/home/user/.lazy-locker"));
434 assert!(wrapper.contains("def main()"));
435 }
436}