shep 0.25.1

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! `shep secret`: the CLI half of [`shep_core::secrets`].
//!
//! No [`Client`](shep_client::Client) anywhere in this module, for
//! [`crate::commands::kv`]'s reason: filling the store before the first
//! `shep start` is the ordinary first run, so it has to work with no
//! shepherd running.
//!
//! Reading a value back is gated on `[secrets] allow_read` in `shep.toml`.
//! A value reaches stdout down exactly one path, in `get`.

use std::io::Read;

use shep_core::config::DaemonConfig;
use shep_core::paths::ShepPaths;
use shep_core::secrets::{
    self, ALL_ENVIRONMENTS, ProviderCache, Resolution, SecretError, SecretRef, SecretView,
};

use crate::cli::{Format, SecretArgs, SecretCommand};
use crate::exit::ExitCode;
use crate::output::{
    Render, SecretKeyRow, SecretKeyRows, SecretSlotRow, SecretValueRow, Streams, emit,
    write_outcome,
};

/// The one sentence that tells an operator how to open the read gate.
///
/// Names the file and the line to write, for
/// [`crate::whistle::gate::Control::how_to_open`]'s reason: an operator
/// told only that reading is off will guess, and the likeliest guess is a
/// flag that does not exist.
pub(crate) const HOW_TO_ALLOW_READ: &str = "printing a stored secret back is off; add `[secrets]` with \
     `allow_read = true` to $SHEP_HOME/shep.toml";

/// The exit code each [`SecretError`] maps to.
///
/// `InvalidKey`/`InvalidEnvironment`/`ValueTooLong` are `Usage`: the operator
/// typed it. `FutureVersion`/`Decode` are `InvalidConfig`: the file on disk
/// is the problem.
///
/// `commands::import::dotenv` writes the same store and must refuse alike.
pub(crate) fn exit_code_for(err: &SecretError) -> ExitCode {
    match err {
        SecretError::InvalidKey(_)
        | SecretError::InvalidEnvironment(_)
        | SecretError::ValueTooLong { .. } => ExitCode::Usage,
        SecretError::FutureVersion(_) | SecretError::Decode(_) => ExitCode::InvalidConfig,
        // `SecretError::Io` and any future variant both land here.
        _ => ExitCode::Failure,
    }
}

/// Renders `err` to `streams.err` and returns the code [`exit_code_for`]
/// maps it to.
///
/// No variant of [`SecretError`] carries a value, so this cannot print one.
fn fail(streams: &mut Streams<'_>, err: &SecretError) -> ExitCode {
    let code = exit_code_for(err);
    streams.fail(code, &err.to_string())
}

/// `shep secret`, dispatched to one of its four subcommands.
pub fn secret(streams: &mut Streams<'_>, paths: &ShepPaths, args: &SecretArgs) -> ExitCode {
    match &args.command {
        SecretCommand::Set {
            key,
            value,
            env,
            stdin,
        } => {
            let value = if *stdin {
                match resolve_stdin_value(&mut std::io::stdin().lock()) {
                    Ok(value) => value,
                    Err((code, message)) => return streams.fail(code, &message),
                }
            } else {
                // clap's `required_unless_present = "stdin"` guarantees this.
                value
                    .clone()
                    .expect("clap requires a value unless --stdin is set")
            };
            set(streams, paths, key, env.as_deref(), &value)
        }
        SecretCommand::Get { key, env } => {
            let (config, diagnostic) = daemon_config_diagnosed(paths);
            if let Some(diagnostic) = diagnostic {
                streams.aside(ExitCode::InvalidConfig.code_str(), &diagnostic);
            }
            get(
                streams,
                paths,
                key,
                env.as_deref(),
                config.secrets.allow_read,
                &config.daemon.environment,
            )
        }
        SecretCommand::Unset { key, env } => unset(streams, paths, key, env.as_deref()),
        SecretCommand::List => list(streams, paths),
    }
}

/// `shep.toml` as this verb reads it, or the defaults when there is no file
/// or it will not parse.
///
/// A broken file leaves the gate shut and the host environment at its
/// default, matching [`crate::whistle::gate::resolve_control`].
///
/// Silent about why it fell back, for callers with no stream to say it on.
pub(crate) fn daemon_config(paths: &ShepPaths) -> DaemonConfig {
    daemon_config_diagnosed(paths).0
}

/// [`daemon_config`]'s config, plus a sentence naming the file and the
/// failure when it fell back because the file was unreadable or would not
/// parse.
///
/// An absent file is the ordinary first run and carries no diagnostic.
///
/// Callers that only want `[daemon] environment` use [`host_environment`].
pub(crate) fn daemon_config_diagnosed(paths: &ShepPaths) -> (DaemonConfig, Option<String>) {
    let file = paths.daemon_config.display();
    let text = match std::fs::read_to_string(&paths.daemon_config) {
        Ok(text) => Some(text),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
        Err(err) => {
            let diagnostic = format!("could not read {file}: {err}");
            return (DaemonConfig::default(), Some(diagnostic));
        }
    };
    match DaemonConfig::load(text.as_deref(), &|_| None) {
        Ok(config) => (config, None),
        Err(err) => (DaemonConfig::default(), Some(format!("{file}: {err}"))),
    }
}

/// `[daemon] environment` as [`daemon_config_diagnosed`] reads it, with its
/// diagnostic, if any, printed to `streams.err` before the default is used.
///
/// For the verbs that resolve a sheep's environment with no `--env` and that
/// have a stream to say so on: a default silently standing in for a
/// configured `staging` sends their secrets to the wrong slot.
pub(crate) fn host_environment(streams: &mut Streams<'_>, paths: &ShepPaths) -> String {
    let (config, diagnostic) = daemon_config_diagnosed(paths);
    if let Some(diagnostic) = diagnostic {
        streams.aside(ExitCode::InvalidConfig.code_str(), &diagnostic);
    }
    config.daemon.environment
}

/// `--stdin`'s value: `reader`'s bytes, with at most one trailing `\n`
/// stripped, and one `\r` immediately before it if present, then decoded as
/// UTF-8.
///
/// Only that one newline is trimmed: leading and interior whitespace can be
/// part of a credential.
///
/// Bounded at [`STDIN_READ_CAP`] rather than read whole: nothing over
/// [`secrets::MAX_VALUE_BYTES`] can be stored, so buffering a stream that
/// size lets the pipe decide this process's memory.
///
/// # Errors
/// The read failed, the value is too long, or the bytes are not valid UTF-8.
fn resolve_stdin_value(reader: &mut dyn Read) -> Result<String, (ExitCode, String)> {
    let mut bytes = Vec::new();
    reader
        .take(STDIN_READ_CAP as u64)
        .read_to_end(&mut bytes)
        .map_err(|err| {
            (
                ExitCode::Failure,
                format!("could not read the value from stdin: {err}"),
            )
        })?;
    if bytes.last() == Some(&b'\n') {
        bytes.pop();
        if bytes.last() == Some(&b'\r') {
            bytes.pop();
        }
    }
    if bytes.len() > secrets::MAX_VALUE_BYTES {
        return Err((
            ExitCode::Usage,
            format!(
                "the value read from stdin is over the {}-byte limit",
                secrets::MAX_VALUE_BYTES
            ),
        ));
    }
    String::from_utf8(bytes).map_err(|_utf8_error| {
        (
            ExitCode::Failure,
            "the value read from stdin is not valid UTF-8".to_string(),
        )
    })
}

/// How much of stdin `--stdin` will pull before refusing.
///
/// Two bytes over [`secrets::MAX_VALUE_BYTES`] so a value at exactly the cap
/// followed by `\r\n` still trims to something storable, and one more so
/// anything longer is over the cap after the trim rather than exactly on it.
const STDIN_READ_CAP: usize = secrets::MAX_VALUE_BYTES + 3;

/// `shep secret set <key> (<value> | --stdin) [--env <environment>]`.
///
/// No `--env` means [`ALL_ENVIRONMENTS`], the slot every environment falls
/// back to.
fn set(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    key: &str,
    environment: Option<&str>,
    value: &str,
) -> ExitCode {
    let environment = environment.unwrap_or(ALL_ENVIRONMENTS);
    match secrets::set(&paths.secrets, key, environment, value) {
        Ok(()) => emit_slot(streams, key, environment),
        Err(err) => fail(streams, &err),
    }
}

/// `shep secret get <key> [--env <environment>]`.
///
/// `Format::Table` writes the value and a newline and nothing else: the
/// whole point is `DB_PASSWORD=$(shep secret get DB_PASSWORD)`. `Format::Json`
/// wraps the same value in the standard envelope.
///
/// Exits [`ExitCode::NotFound`] writing nothing, so `get k || echo default` works.
fn get(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    key: &str,
    environment: Option<&str>,
    allow_read: bool,
    host_environment: &str,
) -> ExitCode {
    if !allow_read {
        return streams.fail(ExitCode::InvalidConfig, HOW_TO_ALLOW_READ);
    }

    let found = match environment {
        Some(environment) => secrets::get(&paths.secrets, key, environment),
        None => resolve(paths, key, host_environment),
    };
    match found {
        Ok(Some(value)) => match streams.fmt {
            Format::Table => write_outcome(writeln!(streams.out, "{value}")),
            Format::Json => {
                let row = SecretValueRow {
                    key: key.to_string(),
                    value,
                };
                emit_secret(streams, row)
            }
        },
        Ok(None) => {
            let message = match environment {
                Some(environment) => format!("`{key}` has no value for `{environment}`"),
                None => {
                    format!("`{key}` has no value for `{host_environment}` or `{ALL_ENVIRONMENTS}`")
                }
            };
            streams.fail(ExitCode::NotFound, &message)
        }
        Err(err) => fail(streams, &err),
    }
}

/// What `key` resolves to in `host_environment`: that environment's own
/// slot, then [`ALL_ENVIRONMENTS`].
///
/// `host_environment` is [`get`]'s own parameter, not a sheep's actual
/// environment: this verb takes no sheep name.
///
/// The operator's own store alone. A provider dog's namespace lives in the
/// shepherd's memory and is not an operator's to edit.
///
/// # Errors
/// [`SecretError::InvalidKey`] for a key outside the grammar, which includes
/// any `namespace/key` reference, plus `Io`, `Decode` and `FutureVersion`.
fn resolve(
    paths: &ShepPaths,
    key: &str,
    host_environment: &str,
) -> Result<Option<String>, SecretError> {
    if !secrets::is_name(key) {
        return Err(SecretError::InvalidKey(key.to_string()));
    }
    let view = SecretView::new(
        host_environment.to_string(),
        secrets::all(&paths.secrets)?,
        ProviderCache::default(),
    );
    Ok(
        match view.resolve(&SecretRef {
            namespace: None,
            key,
        }) {
            Resolution::Found(value) => Some(value.to_string()),
            // A reference naming no namespace cannot miss one.
            Resolution::MissingKey | Resolution::MissingNamespace => None,
        },
    )
}

/// `shep secret unset <key> [--env <environment>]`.
///
/// Exits [`ExitCode::NotFound`] for a slot that held nothing, rather than
/// exiting 0 on a no-op an operator would read as success.
fn unset(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    key: &str,
    environment: Option<&str>,
) -> ExitCode {
    let environment = environment.unwrap_or(ALL_ENVIRONMENTS);
    match secrets::unset(&paths.secrets, key, environment) {
        Ok(true) => emit_slot(streams, key, environment),
        Ok(false) => {
            let message = format!("`{key}` has no value for `{environment}`");
            streams.fail(ExitCode::NotFound, &message)
        }
        Err(err) => fail(streams, &err),
    }
}

/// `shep secret list`: every key and the environments it has a value for,
/// in [`secrets::all`]'s `BTreeMap` order.
fn list(streams: &mut Streams<'_>, paths: &ShepPaths) -> ExitCode {
    match secrets::all(&paths.secrets) {
        Ok(entries) => {
            let rows = SecretKeyRows(
                entries
                    .into_iter()
                    .map(|(key, by_environment)| SecretKeyRow {
                        key,
                        environments: by_environment.into_keys().collect(),
                    })
                    .collect(),
            );
            emit_secret(streams, rows)
        }
        Err(err) => fail(streams, &err),
    }
}

/// The one report `set` and `unset` share: which slot changed, never what
/// is in it.
fn emit_slot(streams: &mut Streams<'_>, key: &str, environment: &str) -> ExitCode {
    emit_secret(
        streams,
        SecretSlotRow {
            key: key.to_string(),
            environment: environment.to_string(),
        },
    )
}

/// Renders `row` under the one envelope command every `secret` verb reports.
fn emit_secret<T: Render>(streams: &mut Streams<'_>, row: T) -> ExitCode {
    write_outcome(emit(
        &mut *streams.out,
        streams.fmt,
        "secret",
        row,
        streams.style,
    ))
}

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

    use std::path::Path;

    use shep_core::paths::ShepPaths;
    use shep_core::secrets::ALL_ENVIRONMENTS;

    use crate::cli::{Cli, Format};
    use crate::exit::ExitCode;
    use crate::output::Streams;

    fn streams<'a>(out: &'a mut Vec<u8>, err: &'a mut Vec<u8>) -> Streams<'a> {
        Streams::bare(out, err, Format::Json)
    }

    /// `$SHEP_HOME` is `dir` itself, so `paths.secrets`' parent exists:
    /// `secrets::set` stages via `tempfile_in`, which creates no parent.
    fn paths_in(dir: &Path) -> ShepPaths {
        let home = dir.display().to_string();
        ShepPaths::resolve(&move |key| (key == "SHEP_HOME").then(|| home.clone()), dir)
    }

    /// `shep secret set`, its refusal's stderr as the `Err`.
    fn run_set(
        paths: &ShepPaths,
        key: &str,
        environment: Option<&str>,
        value: &str,
    ) -> Result<(), String> {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = set(
            &mut streams(&mut out, &mut err),
            paths,
            key,
            environment,
            value,
        );
        match code {
            ExitCode::Success => Ok(()),
            _ => Err(String::from_utf8(err).unwrap()),
        }
    }

    /// `shep secret list`'s stdout, its refusal's stderr as the `Err`.
    fn render_list(paths: &ShepPaths) -> Result<String, String> {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = list(&mut streams(&mut out, &mut err), paths);
        match code {
            ExitCode::Success => Ok(String::from_utf8(out).unwrap()),
            _ => Err(String::from_utf8(err).unwrap()),
        }
    }

    /// `shep secret get` against a store whose host environment is
    /// `production`: the code, then stdout, then stderr.
    fn run_get(
        paths: &ShepPaths,
        key: &str,
        environment: Option<&str>,
        allow_read: bool,
        fmt: Format,
    ) -> (ExitCode, String, String) {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = get(
            &mut Streams::bare(&mut out, &mut err, fmt),
            paths,
            key,
            environment,
            allow_read,
            "production",
        );
        (
            code,
            String::from_utf8(out).unwrap(),
            String::from_utf8(err).unwrap(),
        )
    }

    /// [`run_get`]'s stderr half, under [`Format::Table`]: every caller
    /// below is after the refusal text, not the envelope shape.
    fn run_get_capturing(
        paths: &ShepPaths,
        key: &str,
        environment: Option<&str>,
        allow_read: bool,
    ) -> (ExitCode, String) {
        let (code, _, err) = run_get(paths, key, environment, allow_read, Format::Table);
        (code, err)
    }

    /// [`run_get`]'s stdout half, under [`Format::Table`]: the bare-value
    /// contract `shep secret get k || echo default` and
    /// `DB_PASSWORD=$(shep secret get DB_PASSWORD)` depend on.
    /// [`get_under_json_wraps_the_value_in_the_standard_envelope`] covers
    /// the other format.
    fn run_get_capturing_out(
        paths: &ShepPaths,
        key: &str,
        environment: Option<&str>,
        allow_read: bool,
    ) -> (ExitCode, String) {
        let (code, out, _) = run_get(paths, key, environment, allow_read, Format::Table);
        (code, out)
    }

    /// `shep secret get K` through the dispatcher, so `shep.toml` is read
    /// the way an operator's run reads it: the code, then stderr.
    ///
    /// Under [`Format::Table`], not JSON: the JSON envelope escapes a
    /// Windows path's backslashes, so a path assertion would never match.
    fn run_get_verb(paths: &ShepPaths) -> (ExitCode, String) {
        use clap::Parser;

        let cli = Cli::try_parse_from(["shep", "secret", "get", "K"]).unwrap();
        let crate::cli::Commands::Secret(args) = cli.command else {
            panic!("expected Commands::Secret");
        };
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = secret(
            &mut Streams::bare(&mut out, &mut err, Format::Table),
            paths,
            &args,
        );
        (code, String::from_utf8(err).unwrap())
    }

    /// fails if a `shep.toml` that will not parse goes back to reading as
    /// the defaults with nothing said: the operator would see only that
    /// reading is off, and never that their `allow_read = true` was never
    /// read.
    #[test]
    fn get_names_a_shep_toml_that_will_not_parse() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "v").unwrap();
        std::fs::write(&paths.daemon_config, "[secrets\nallow_read = true\n").unwrap();

        let (code, err) = run_get_verb(&paths);

        assert_eq!(code, ExitCode::InvalidConfig, "the gate stays shut");
        assert!(
            err.contains(&paths.daemon_config.display().to_string()),
            "{err}"
        );
        assert!(err.contains("invalid shep.toml"), "{err}");
    }

    /// fails if a `shep.toml` that exists but cannot be read is treated as
    /// absent. A directory in its place stands in for a permissions or disk
    /// error: both are an `Err` from `read_to_string` that is not `NotFound`.
    #[test]
    fn get_names_a_shep_toml_that_cannot_be_read() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        std::fs::create_dir(&paths.daemon_config).unwrap();

        let (code, err) = run_get_verb(&paths);

        assert_eq!(code, ExitCode::InvalidConfig, "the gate stays shut");
        assert!(
            err.contains(&paths.daemon_config.display().to_string()),
            "{err}"
        );
        assert!(err.contains("could not read"), "{err}");
    }

    /// fails if an absent `shep.toml` starts warning: no file is the
    /// ordinary first run, and the refusal alone says how to open the gate.
    #[test]
    fn get_says_nothing_extra_about_an_absent_shep_toml() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());

        let (code, err) = run_get_verb(&paths);

        assert_eq!(code, ExitCode::InvalidConfig);
        assert!(!err.contains("could not read"), "{err}");
        assert!(!err.contains("invalid shep.toml"), "{err}");
    }

    /// fails if `import dotenv` and `describe` go back to a silent default:
    /// the environment they fall to is the wrong slot for an operator whose
    /// `[daemon] environment` is `staging` in a file that will not parse.
    #[test]
    fn host_environment_names_a_shep_toml_that_will_not_parse() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        std::fs::write(
            &paths.daemon_config,
            "[daemon]\nenvironment = \"staging\"\n[secrets\n",
        )
        .unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();

        let environment = host_environment(&mut streams(&mut out, &mut err), &paths);

        assert_eq!(environment, DaemonConfig::default().daemon.environment);
        let err = String::from_utf8(err).unwrap();
        assert!(err.contains("invalid shep.toml"), "{err}");
    }

    #[test]
    fn host_environment_reads_a_good_shep_toml_without_comment() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        std::fs::write(
            &paths.daemon_config,
            "[daemon]\nenvironment = \"staging\"\n",
        )
        .unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();

        let environment = host_environment(&mut streams(&mut out, &mut err), &paths);

        assert_eq!(environment, "staging");
        assert!(err.is_empty(), "{err:?}");
    }

    #[test]
    fn set_then_list_names_the_key_and_its_environments_but_no_value() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "DB_PASSWORD", None, "hunter2").unwrap();
        run_set(&paths, "DB_PASSWORD", Some("staging"), "staging-pw").unwrap();

        let listed = render_list(&paths).unwrap();
        assert!(listed.contains("DB_PASSWORD"));
        assert!(listed.contains("all"));
        assert!(listed.contains("staging"));
        assert!(!listed.contains("hunter2"), "a list never prints a value");
        assert!(!listed.contains("staging-pw"));
    }

    #[test]
    fn set_with_no_env_writes_the_all_slot() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "v").unwrap();
        assert_eq!(
            shep_core::secrets::get(&paths.secrets, "K", ALL_ENVIRONMENTS)
                .unwrap()
                .as_deref(),
            Some("v")
        );
    }

    #[test]
    fn get_is_refused_unless_shep_toml_turns_it_on() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "v").unwrap();

        let (code, err) = run_get_capturing(&paths, "K", None, /* allow_read */ false);
        assert_eq!(code, ExitCode::InvalidConfig);
        assert!(err.contains("allow_read"), "{err}");
        assert!(err.contains("[secrets]"), "{err}");
        assert!(
            !err.contains('v') || !err.contains("value is"),
            "no value in the refusal"
        );
    }

    #[test]
    fn get_prints_the_value_once_it_is_turned_on() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "v").unwrap();
        let (code, out) = run_get_capturing_out(&paths, "K", None, /* allow_read */ true);
        assert_eq!(code, ExitCode::Success);
        assert_eq!(out.trim(), "v");
    }

    /// fails if `--format json` goes back to the bare value: a bare
    /// `hunter2` is not JSON at all, so `shep secret get K --format json |
    /// jq .` would fail outright, and it would be an undocumented second
    /// exception to the envelope contract beside `bleats`.
    #[test]
    fn get_under_json_wraps_the_value_in_the_standard_envelope() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "hunter2").unwrap();

        let (code, out, _) = run_get(&paths, "K", None, true, Format::Json);
        assert_eq!(code, ExitCode::Success);
        let envelope: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
        assert_eq!(envelope["command"], "secret");
        assert_eq!(envelope["data"]["key"], "K");
        assert_eq!(envelope["data"]["value"], "hunter2");
    }

    #[test]
    fn get_on_a_missing_key_exits_not_found_and_prints_nothing() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        let (code, out) = run_get_capturing_out(&paths, "ABSENT", None, true);
        assert_eq!(
            code,
            ExitCode::NotFound,
            "so `shep secret get k || default` works"
        );
        assert!(out.is_empty());
    }

    #[test]
    fn a_bad_key_exits_usage_and_a_future_store_exits_invalid_config() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        assert_eq!(
            exit_code_for(&SecretError::InvalidKey("x y".into())),
            ExitCode::Usage
        );
        assert_eq!(
            exit_code_for(&SecretError::FutureVersion(9)),
            ExitCode::InvalidConfig
        );
        let _ = paths;
    }

    /// The door an operator uses, not [`exit_code_for`] on its own: a bad
    /// key is refused before the file is opened, so a typo cannot leave a
    /// store behind.
    #[test]
    fn a_bad_key_is_refused_through_set_and_creates_no_store() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = set(
            &mut streams(&mut out, &mut err),
            &paths,
            "not valid",
            None,
            "v",
        );
        assert_eq!(code, ExitCode::Usage);
        assert!(
            !paths.secrets.exists(),
            "the store must not be created on a refused key"
        );
    }

    /// fails if `--env` starts falling back to `all`. An operator asking
    /// what `staging` holds is asking about that slot, and answering with
    /// production's shared value would report a slot that is empty as
    /// filled.
    #[test]
    fn get_with_an_env_reads_that_slot_exactly() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "shared").unwrap();

        let (code, out) = run_get_capturing_out(&paths, "K", Some("staging"), true);
        assert_eq!(code, ExitCode::NotFound);
        assert!(out.is_empty(), "{out}");

        run_set(&paths, "K", Some("staging"), "staged").unwrap();
        let (code, out) = run_get_capturing_out(&paths, "K", Some("staging"), true);
        assert_eq!(code, ExitCode::Success);
        assert_eq!(out.trim(), "staged");
    }

    /// fails if either report grows the value it just wrote or removed.
    /// `shep secret set` runs in terminals and in CI logs, and a value
    /// echoed there outlives the command.
    #[test]
    fn set_and_unset_report_the_slot_and_never_the_value() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        let mut out = Vec::new();
        let mut err = Vec::new();

        let code = set(
            &mut streams(&mut out, &mut err),
            &paths,
            "K",
            Some("staging"),
            "hunter2",
        );
        assert_eq!(code, ExitCode::Success);
        let written = String::from_utf8(std::mem::take(&mut out)).unwrap();
        assert!(written.contains("K"), "{written}");
        assert!(written.contains("staging"), "{written}");
        assert!(!written.contains("hunter2"), "{written}");

        let code = unset(
            &mut streams(&mut out, &mut err),
            &paths,
            "K",
            Some("staging"),
        );
        assert_eq!(code, ExitCode::Success);
        let removed = String::from_utf8(out).unwrap();
        assert!(removed.contains("staging"), "{removed}");
        assert!(!removed.contains("hunter2"), "{removed}");
    }

    /// fails if an unset that removed nothing starts exiting 0, which an
    /// operator would read as a value having been there.
    #[test]
    fn unset_on_an_empty_slot_exits_not_found() {
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = unset(&mut streams(&mut out, &mut err), &paths, "ABSENT", None);
        assert_eq!(code, ExitCode::NotFound);
        assert!(out.is_empty(), "{out:?}");
    }

    #[test]
    fn the_store_works_with_no_shepherd_running() {
        // The whole reason this verb touches the file directly. If this test
        // ever needs a daemon, the design has been broken.
        let home = tempfile::tempdir().unwrap();
        let paths = paths_in(home.path());
        run_set(&paths, "K", None, "v").unwrap();
        assert!(paths.secrets.exists());
    }

    /// Covers `printf %s "$PW" | shep secret set KEY --stdin`: no trailing
    /// newline at all, so nothing is trimmed.
    #[test]
    fn stdin_value_reads_bytes_with_no_trailing_newline() {
        let mut input = std::io::Cursor::new(b"hunter2".to_vec());
        assert_eq!(resolve_stdin_value(&mut input).unwrap(), "hunter2");
    }

    /// Covers `echo "$PW" | shep secret set KEY --stdin` on both a unix
    /// pipe (`\n`) and a Windows one (`\r\n`): exactly one trailing newline
    /// comes off, so both store the same value.
    #[test]
    fn stdin_value_strips_exactly_one_trailing_newline_and_a_preceding_cr() {
        let mut lf = std::io::Cursor::new(b"hunter2\n".to_vec());
        assert_eq!(resolve_stdin_value(&mut lf).unwrap(), "hunter2");

        let mut crlf = std::io::Cursor::new(b"hunter2\r\n".to_vec());
        assert_eq!(resolve_stdin_value(&mut crlf).unwrap(), "hunter2");
    }

    /// fails if trimming widens past that one newline: leading and interior
    /// whitespace, and a `\r` anywhere but immediately before the final
    /// `\n`, can be part of the credential and must survive.
    #[test]
    fn stdin_value_trims_nothing_else() {
        let mut input = std::io::Cursor::new(b" hunter2 \r more\n".to_vec());
        assert_eq!(resolve_stdin_value(&mut input).unwrap(), " hunter2 \r more");
    }

    /// A reader holding `left` bytes of `x`, counting what was pulled out
    /// of it.
    struct Oversized {
        left: usize,
        pulled: usize,
    }

    impl Read for Oversized {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let taken = buf.len().min(self.left);
            buf[..taken].fill(b'x');
            self.left -= taken;
            self.pulled += taken;
            Ok(taken)
        }
    }

    /// fails if the read is unbounded: an input nothing will accept must be
    /// refused off the front of the stream rather than buffered whole and
    /// then handed to `secrets::set` to reject. The code has to stay
    /// `Usage`, which is what the positional form's `ValueTooLong` exits.
    #[test]
    fn stdin_value_refuses_an_oversized_reader_without_buffering_it() {
        let mut input = Oversized {
            left: secrets::MAX_VALUE_BYTES * 4,
            pulled: 0,
        };

        let (code, message) = resolve_stdin_value(&mut input).unwrap_err();

        assert_eq!(code, ExitCode::Usage);
        assert!(
            message.contains(&secrets::MAX_VALUE_BYTES.to_string()),
            "the refusal names the limit: {message}"
        );
        assert!(
            input.pulled <= secrets::MAX_VALUE_BYTES + 8,
            "only a little past the cap may be read, not the whole stream: {}",
            input.pulled
        );
    }

    /// fails if the bound is drawn so tight that a value at exactly the cap
    /// stops fitting: `echo` appends a newline, so the longest storable
    /// value arrives as `MAX_VALUE_BYTES` plus `\r\n`.
    #[test]
    fn stdin_value_accepts_a_value_at_the_cap_with_a_newline_after_it() {
        let mut at_cap =
            std::io::Cursor::new([vec![b'x'; secrets::MAX_VALUE_BYTES], b"\r\n".to_vec()].concat());
        assert_eq!(
            resolve_stdin_value(&mut at_cap).unwrap().len(),
            secrets::MAX_VALUE_BYTES
        );
    }

    /// fails if `set K --stdin` stops parsing with no positional value: the
    /// whole point of the flag is a value with no argument at all.
    #[test]
    fn set_stdin_alone_parses_with_no_positional_value() {
        use clap::Parser;

        let cli = Cli::try_parse_from(["shep", "secret", "set", "K", "--stdin"]).unwrap();
        let crate::cli::Commands::Secret(args) = cli.command else {
            panic!("expected Commands::Secret");
        };
        let SecretCommand::Set { value, stdin, .. } = args.command else {
            panic!("expected SecretCommand::Set");
        };
        assert_eq!(value, None);
        assert!(stdin);
    }

    /// A positional value and `--stdin` disagree about where the value
    /// comes from; clap refuses before either is ever read, naming both.
    #[test]
    fn set_refuses_a_positional_value_and_stdin_together() {
        use clap::Parser;
        assert!(Cli::try_parse_from(["shep", "secret", "set", "K", "v", "--stdin"]).is_err());
    }

    /// Neither a positional value nor `--stdin` leaves nothing to store.
    #[test]
    fn set_requires_a_positional_value_or_stdin() {
        use clap::Parser;
        assert!(Cli::try_parse_from(["shep", "secret", "set", "K"]).is_err());
        assert!(Cli::try_parse_from(["shep", "secret", "set", "K", "v"]).is_ok());
        assert!(Cli::try_parse_from(["shep", "secret", "set", "K", "--stdin"]).is_ok());
    }
}