redisctl-core 0.12.1

Core library for Redis CLI tools - config, workflows, and shared logic
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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Credential delivery to a dotenv file (PRD §4.4/§5.3).
//!
//! The `quick-database` workflow never prints the connection string to stdout/stderr; it
//! writes it to a file so it can't leak into terminal scrollback, CI logs, or an agent's
//! captured output. This module owns that file I/O and the git-hygiene follow-up, with no
//! dependency on the API layer so it can be unit-tested in isolation.

use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};

use thiserror::Error;

#[derive(Debug, Error)]
pub enum DeliveryError {
    #[error("failed to access {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("refusing to write credentials to {path}: {reason}")]
    Refused { path: String, reason: String },
}

impl DeliveryError {
    fn io(path: &Path, source: std::io::Error) -> Self {
        Self::Io {
            path: path.display().to_string(),
            source,
        }
    }

    fn refused(path: &Path, reason: &str) -> Self {
        Self::Refused {
            path: path.display().to_string(),
            reason: reason.to_string(),
        }
    }
}

/// What `deliver`/`deliver_vars` did, for reporting and tests.
#[derive(Debug, Clone)]
pub struct DeliveryOutcome {
    /// The file that was written.
    pub path: PathBuf,
    /// The primary variable name written into it (the first of the set).
    pub variable: String,
    /// True when the target file did not exist and was created fresh.
    pub created: bool,
    /// True when at least one existing `VAR=` line was replaced (re-run / reuse path).
    pub replaced: bool,
}

/// Whether `name` can be written as a dotenv key.
///
/// The keys reach the file through `format!("{k}={v}")`, so a name carrying a newline or an `=`
/// would write assignments of its own. Callers validate their own input for a better error; this
/// is what makes it impossible to skip.
pub fn is_env_var_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Whether `value` can be written as a dotenv value.
///
/// The other half of `format!("{k}={v}")`: a value carrying a line break ends the assignment and
/// writes whatever follows as a line of its own. Values here are upstream-supplied — a database
/// password can be set in the Redis Cloud console, and the broken-out password field is delivered
/// raw so apps can use it directly — so the caller is not the only one who decides what arrives.
pub fn is_env_var_value(value: &str) -> bool {
    !value.contains('\n') && !value.contains('\r')
}

/// Append (or replace) a single `variable=value` in the dotenv file at `path`.
/// Convenience wrapper over [`deliver_vars`].
pub fn deliver(path: &Path, variable: &str, value: &str) -> Result<DeliveryOutcome, DeliveryError> {
    deliver_vars(path, &[(variable, value)])
}

/// Write a set of `KEY=value` pairs into the dotenv file at `path` in one pass.
///
/// - target exists → each existing `KEY=` line is replaced in place rather than duplicated
///   (idempotent re-run), all other lines are preserved byte-for-byte, and any genuinely new
///   keys are appended under a single `# --- added by redisctl … ---` marker. The file is
///   only rewritten when the content actually changes.
/// - target missing → created with mode `0o600` (unix), a marker, and all pairs.
///
/// No backups are made: unrelated lines are never touched, so the only thing an overwrite
/// changes is the managed keys — exactly what the caller asked for.
///
/// `vars` must be non-empty; the first pair is treated as the primary variable for reporting.
pub fn deliver_vars(path: &Path, vars: &[(&str, &str)]) -> Result<DeliveryOutcome, DeliveryError> {
    let primary = vars.first().map(|(k, _)| k.to_string()).unwrap_or_default();

    if let Some((key, _)) = vars.iter().find(|(k, _)| !is_env_var_name(k)) {
        return Err(DeliveryError::refused(
            path,
            &format!("'{key}' is not an environment variable name"),
        ));
    }
    // The value is not quoted or escaped on the way in, so a line break in one would write the
    // rest as its own assignment — and `upsert_vars` would not match that line on a re-run, so
    // it would outlive every later delivery.
    if let Some((key, _)) = vars.iter().find(|(_, v)| !is_env_var_value(v)) {
        return Err(DeliveryError::refused(
            path,
            &format!("the value for '{key}' contains a line break"),
        ));
    }

    if fs::symlink_metadata(path)
        .map(|m| m.file_type().is_symlink())
        .unwrap_or(false)
    {
        return Err(DeliveryError::refused(
            path,
            "the path is a symlink; writing credentials through it could target a file you did \
             not choose",
        ));
    }

    if path.exists() {
        let original = fs::read_to_string(path).map_err(|e| DeliveryError::io(path, e))?;
        let (rewritten, replaced) = upsert_vars(&original, vars);
        if rewritten != original {
            fs::write(path, &rewritten).map_err(|e| DeliveryError::io(path, e))?;
        }
        // The file holds credentials now — ensure it isn't group/world-readable, even if it
        // pre-existed with looser permissions (a fresh file is created 0600 below, but an
        // existing 0644 .env would otherwise stay readable after we write the password).
        restrict_permissions(path)?;
        Ok(DeliveryOutcome {
            path: path.to_path_buf(),
            variable: primary,
            created: false,
            replaced,
        })
    } else {
        let mut contents = format!("{}\n", marker_comment());
        for (k, v) in vars {
            contents.push_str(&format!("{k}={v}\n"));
        }
        write_new_private(path, &contents)?;
        Ok(DeliveryOutcome {
            path: path.to_path_buf(),
            variable: primary,
            created: true,
            replaced: false,
        })
    }
}

/// If `path` sits inside a git working tree and isn't already ignored, append it to the
/// repo-root `.gitignore`. Outside a git repo this is a silent no-op (PRD §7.2). Returns
/// `true` iff `.gitignore` was modified.
pub fn ensure_gitignored(path: &Path) -> Result<bool, DeliveryError> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        match std::env::current_dir() {
            Ok(cwd) => cwd.join(path),
            Err(_) => return Ok(false),
        }
    };

    let Some(repo_root) = find_repo_root(&abs) else {
        return Ok(false); // not a git repo → skip
    };

    // Entry to add: path relative to the repo root when possible, else the bare file name.
    let entry = abs
        .strip_prefix(&repo_root)
        .ok()
        .map(|p| p.to_string_lossy().replace('\\', "/"))
        .or_else(|| abs.file_name().map(|n| n.to_string_lossy().into_owned()))
        .unwrap_or_default();
    if entry.is_empty() {
        return Ok(false);
    }
    let file_name = abs
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default();

    let gitignore = repo_root.join(".gitignore");
    let existing = fs::read_to_string(&gitignore).unwrap_or_default();
    if already_ignored(&existing, &entry, &file_name) {
        return Ok(false);
    }

    let mut contents = existing;
    if !contents.is_empty() && !contents.ends_with('\n') {
        contents.push('\n');
    }
    contents.push_str(&entry);
    contents.push('\n');
    fs::write(&gitignore, &contents).map_err(|e| DeliveryError::io(&gitignore, e))?;
    Ok(true)
}

fn marker_comment() -> String {
    format!(
        "# --- added by redisctl on {} ---",
        chrono::Local::now().format("%Y-%m-%d")
    )
}

/// Replace each existing `KEY=…` line in place; append the remaining (new) keys under a
/// single marker. Returns the new content and whether at least one line was replaced. All
/// non-matching lines are preserved byte-for-byte.
fn upsert_vars(original: &str, vars: &[(&str, &str)]) -> (String, bool) {
    let mut remaining: Vec<(&str, &str)> = vars.to_vec();
    let mut replaced_any = false;
    let mut out_lines: Vec<String> = Vec::new();
    let mut written: Vec<&str> = Vec::new();

    for line in original.lines() {
        let trimmed = line.trim_start();
        match vars
            .iter()
            .find(|(k, _)| trimmed.starts_with(&format!("{k}=")))
        {
            Some((k, v)) => {
                remaining.retain(|(rk, _)| rk != k);
                replaced_any = true;
                if written.contains(k) {
                    continue;
                }
                written.push(k);
                out_lines.push(format!("{k}={v}"));
            }
            None => out_lines.push(line.to_string()),
        }
    }

    let mut out = out_lines.join("\n");
    // Preserve a trailing newline if the original had one (byte-for-byte for the kept lines).
    if original.ends_with('\n') {
        out.push('\n');
    }

    // Append any keys that had no existing line, under one marker.
    if !remaining.is_empty() {
        if !out.is_empty() && !out.ends_with('\n') {
            out.push('\n');
        }
        out.push_str(&marker_comment());
        out.push('\n');
        for (k, v) in &remaining {
            out.push_str(&format!("{k}={v}\n"));
        }
    }

    (out, replaced_any)
}

#[cfg(unix)]
fn write_new_private(path: &Path, contents: &str) -> Result<(), DeliveryError> {
    use std::os::unix::fs::OpenOptionsExt;
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .map_err(|e| DeliveryError::io(path, e))?;
    file.write_all(contents.as_bytes())
        .map_err(|e| DeliveryError::io(path, e))
}

// Windows has no POSIX mode bits; create the file normally and rely on the user profile's
// ACLs. Documented limitation (PRD §5.3).
#[cfg(not(unix))]
fn write_new_private(path: &Path, contents: &str) -> Result<(), DeliveryError> {
    fs::write(path, contents).map_err(|e| DeliveryError::io(path, e))
}

/// Tighten an existing credentials file to owner-only (`0o600`) on unix. No-op elsewhere.
#[cfg(unix)]
fn restrict_permissions(path: &Path) -> Result<(), DeliveryError> {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
        .map_err(|e| DeliveryError::io(path, e))
}

#[cfg(not(unix))]
fn restrict_permissions(_path: &Path) -> Result<(), DeliveryError> {
    Ok(())
}

fn find_repo_root(start: &Path) -> Option<PathBuf> {
    // `start` is a file path; begin at its directory.
    let mut dir = start.parent();
    while let Some(d) = dir {
        if d.join(".git").exists() {
            return Some(d.to_path_buf());
        }
        dir = d.parent();
    }
    None
}

fn already_ignored(gitignore: &str, entry: &str, file_name: &str) -> bool {
    gitignore.lines().any(|line| {
        let l = line.trim();
        if l.is_empty() || l.starts_with('#') {
            return false;
        }
        let l = l.trim_start_matches("./");
        l == entry || l == file_name
    })
}

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

    #[test]
    fn creates_fresh_file_with_marker() {
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        let out = deliver(&env, "REDIS_URL", "rediss://x@h:1").unwrap();
        assert!(out.created);
        assert!(!out.replaced);
        let body = fs::read_to_string(&env).unwrap();
        assert!(body.contains("REDIS_URL=rediss://x@h:1"));
        assert!(body.contains("added by redisctl"));
    }

    #[cfg(unix)]
    #[test]
    fn existing_loose_file_is_tightened_to_0600() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        fs::write(&env, "EXISTING=1\n").unwrap();
        fs::set_permissions(&env, fs::Permissions::from_mode(0o644)).unwrap();
        // Writing secrets into a pre-existing world-readable file must tighten it.
        deliver(&env, "REDIS_URL", "rediss://x@h:1").unwrap();
        let mode = fs::metadata(&env).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    #[cfg(unix)]
    #[test]
    fn fresh_file_is_0600() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        deliver(&env, "REDIS_URL", "rediss://x@h:1").unwrap();
        let mode = fs::metadata(&env).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    #[test]
    fn existing_file_is_appended_preserving_others() {
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        fs::write(&env, "EXISTING=1\nOTHER=two\n").unwrap();
        let out = deliver(&env, "REDIS_URL", "rediss://x@h:1").unwrap();
        assert!(!out.created);
        assert!(!out.replaced);
        let body = fs::read_to_string(&env).unwrap();
        // Unrelated lines preserved byte-for-byte at the head; no backup file created.
        assert!(body.starts_with("EXISTING=1\nOTHER=two\n"));
        assert!(body.contains("REDIS_URL=rediss://x@h:1"));
        assert_eq!(
            fs::read_dir(dir.path()).unwrap().count(),
            1,
            "only .env exists, no backup"
        );
    }

    #[test]
    fn writes_multiple_vars_and_reruns_cleanly() {
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        let vars = [
            ("REDIS_URL", "rediss://default:p@h:1"),
            ("REDIS_HOST", "h"),
            ("REDIS_PORT", "1"),
        ];
        let out = deliver_vars(&env, &vars).unwrap();
        assert!(out.created);
        assert_eq!(out.variable, "REDIS_URL");
        let body = fs::read_to_string(&env).unwrap();
        for (k, v) in vars {
            assert!(body.contains(&format!("{k}={v}")), "missing {k}");
        }

        // Re-run with new values: every key is replaced in place, none duplicated.
        let vars2 = [
            ("REDIS_URL", "rediss://default:p2@h2:2"),
            ("REDIS_HOST", "h2"),
            ("REDIS_PORT", "2"),
        ];
        let out2 = deliver_vars(&env, &vars2).unwrap();
        assert!(out2.replaced);
        let body2 = fs::read_to_string(&env).unwrap();
        assert_eq!(body2.matches("REDIS_URL=").count(), 1);
        assert_eq!(body2.matches("REDIS_HOST=").count(), 1);
        assert_eq!(body2.matches("REDIS_PORT=").count(), 1);
        assert!(body2.contains("REDIS_HOST=h2"));
        assert!(!body2.contains("REDIS_HOST=h\n"));
    }

    #[test]
    fn unchanged_rerun_is_noop() {
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        deliver(&env, "REDIS_URL", "rediss://x@h:1").unwrap();
        let before = fs::read_to_string(&env).unwrap();

        // Identical re-run: content stable, no extra files.
        let out = deliver(&env, "REDIS_URL", "rediss://x@h:1").unwrap();
        assert!(!out.created);
        assert_eq!(fs::read_to_string(&env).unwrap(), before);
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    #[test]
    fn rerun_replaces_not_duplicates() {
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        deliver(&env, "REDIS_URL", "rediss://old@h:1").unwrap();
        let out = deliver(&env, "REDIS_URL", "rediss://new@h:2").unwrap();
        assert!(out.replaced);
        let body = fs::read_to_string(&env).unwrap();
        assert_eq!(body.matches("REDIS_URL=").count(), 1, "no duplicate var");
        assert!(body.contains("REDIS_URL=rediss://new@h:2"));
        assert!(!body.contains("rediss://old@h:1"));
    }

    #[test]
    fn gitignore_appended_in_repo() {
        let dir = tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        let env = dir.path().join(".env");
        fs::write(&env, "A=1\n").unwrap();
        let changed = ensure_gitignored(&env).unwrap();
        assert!(changed);
        let gi = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(gi.lines().any(|l| l.trim() == ".env"));
    }

    #[test]
    fn gitignore_skipped_outside_repo() {
        let dir = tempdir().unwrap();
        let env = dir.path().join(".env");
        fs::write(&env, "A=1\n").unwrap();
        assert!(!ensure_gitignored(&env).unwrap());
        assert!(!dir.path().join(".gitignore").exists());
    }

    #[test]
    fn gitignore_not_duplicated_when_already_ignored() {
        let dir = tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::write(dir.path().join(".gitignore"), "node_modules\n.env\n").unwrap();
        let env = dir.path().join(".env");
        fs::write(&env, "A=1\n").unwrap();
        let changed = ensure_gitignored(&env).unwrap();
        assert!(!changed);
        let gi = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert_eq!(gi.matches(".env").count(), 1);
    }

    /// A duplicate key must not survive the rewrite: dotenv loaders honour the last occurrence,
    /// so a leftover second line would silently win with the stale value.
    #[test]
    fn upsert_replaces_every_occurrence_of_a_key() {
        let original = "REDIS_URL=old-one\nOTHER=keep\nREDIS_URL=old-two\n";
        let (out, replaced) = upsert_vars(original, &[("REDIS_URL", "new")]);
        assert!(replaced);
        assert_eq!(out.matches("REDIS_URL=").count(), 1, "got {out:?}");
        assert!(out.contains("REDIS_URL=new"));
        assert!(!out.contains("old-two"));
        assert!(out.contains("OTHER=keep"), "unrelated lines are preserved");
    }

    #[cfg(unix)]
    #[test]
    fn deliver_refuses_a_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real-file");
        std::fs::write(&target, "SECRET=already-here\n").unwrap();
        let link = dir.path().join("link.env");
        std::os::unix::fs::symlink(&target, &link).unwrap();

        let err = deliver_vars(&link, &[("REDIS_URL", "redis://x")]).unwrap_err();
        assert!(matches!(err, DeliveryError::Refused { .. }), "got {err:?}");
        assert_eq!(
            std::fs::read_to_string(&target).unwrap(),
            "SECRET=already-here\n",
            "the symlink target must be untouched"
        );
    }

    /// The keys are interpolated as `KEY=value`, so a name carrying a newline or an `=` would
    /// write assignments of its own. Refused here, whatever the caller validated.
    #[test]
    fn deliver_refuses_a_key_that_is_not_an_env_var_name() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".env");

        for bad in [
            "A\nINJECTED=1",
            "A\r\nINJECTED=1",
            "REDIS_URL=x",
            "HAS-DASH",
            "HAS SPACE",
            "1LEADING",
            "",
        ] {
            let err = deliver_vars(&path, &[(bad, "redis://x")]).unwrap_err();
            assert!(
                matches!(err, DeliveryError::Refused { .. }),
                "{bad:?} gave {err:?}"
            );
            assert!(!path.exists(), "{bad:?} created a file");
        }

        // A later pair is checked too, not just the primary one.
        let err = deliver_vars(&path, &[("REDIS_URL", "redis://x"), ("A\nB", "y")]).unwrap_err();
        assert!(matches!(err, DeliveryError::Refused { .. }), "got {err:?}");
        assert!(!path.exists(), "a rejected set wrote a file anyway");
    }

    /// The value is interpolated unquoted, so a line break in one writes an assignment of its
    /// own. Values are upstream-supplied (a console-set database password reaches the raw
    /// `_PASSWORD` field), so the key check alone does not close the hole.
    #[test]
    fn deliver_refuses_a_value_carrying_a_line_break() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".env");

        for bad in ["p\nINJECTED=owned", "p\r\nINJECTED=owned", "p\r", "\n"] {
            let err = deliver_vars(&path, &[("REDIS_PASSWORD", bad)]).unwrap_err();
            assert!(
                matches!(err, DeliveryError::Refused { .. }),
                "{bad:?} gave {err:?}"
            );
            assert!(!path.exists(), "{bad:?} created a file");
        }

        // A later pair is checked too, and a rejected set writes nothing at all.
        let err = deliver_vars(
            &path,
            &[("REDIS_URL", "redis://x"), ("REDIS_PASSWORD", "p\nX=1")],
        )
        .unwrap_err();
        assert!(matches!(err, DeliveryError::Refused { .. }), "got {err:?}");
        assert!(!path.exists(), "a rejected set wrote a file anyway");

        // An existing file is left untouched rather than half-updated.
        deliver_vars(&path, &[("REDIS_URL", "redis://ok")]).unwrap();
        let before = fs::read_to_string(&path).unwrap();
        assert!(deliver_vars(&path, &[("REDIS_URL", "redis://x\nX=1")]).is_err());
        assert_eq!(fs::read_to_string(&path).unwrap(), before);
    }
}