shep 0.18.2

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
use super::super::*;

impl App {
    /// `Enter` on the secrets pane while nothing is armed: opens the
    /// `+ new key` row's name input, or the selected key's value input.
    /// Refuses a provider row (read-only here) and a read-only lookout,
    /// each with its own reason, through [`Self::authorize_write`] for the
    /// second.
    ///
    /// The gate is checked before the input opens, not just before the
    /// write: a refusal that arrived only once a whole value was typed
    /// would waste every one of those keystrokes for nothing.
    pub(in crate::lookout::app) fn secrets_confirm(&mut self) -> Effect {
        // `environments` empty is the placeholder model `KeyPress::Secrets`
        // opens with, before the first `Msg::Secrets` lands: `selected` (0)
        // and `model.rows.len()` (also 0) coincide there by having no rows
        // yet either, the same trap `Msg::Secrets`'s own clamp guards
        // against. A real load never has an empty `environments`: the model
        // always carries `all`, even over an empty store.
        let is_new_key_row = matches!(
            &self.body,
            Body::Secrets(pane)
                if !pane.model.environments.is_empty() && pane.selected_is_new_key_row()
        );
        if is_new_key_row {
            if self.authorize_write().is_none() {
                return Effect::None;
            }
            let Some(pane) = self.secrets_pane_mut() else {
                return Effect::None;
            };
            pane.typing = Some(Typing {
                what: TypingWhat::NewKey,
                buffer: TextBox::new(),
            });
            self.mode = InputMode::Text;
            return Effect::None;
        }
        let Some(row) = (match &self.body {
            Body::Secrets(pane) => pane.model.rows.get(pane.selected).cloned(),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Sheep(_) => None,
        }) else {
            return Effect::None;
        };
        if self.refuse_provider_row(&row) {
            return Effect::None;
        }
        if self.authorize_write().is_none() {
            return Effect::None;
        }
        let Some(pane) = self.secrets_pane_mut() else {
            return Effect::None;
        };
        // Seeded empty, never with the stored value: showing it here would
        // put a secret on screen with none of the reveal gate's ten-second
        // limit or its own `[secrets] allow_read` check.
        pane.typing = Some(Typing {
            what: TypingWhat::ValueFor(row.key),
            buffer: TextBox::new(),
        });
        self.mode = InputMode::Text;
        Effect::None
    }

    /// The secrets pane's own text keymap, in force while
    /// [`SecretsPane::typing`] owns [`InputMode::Text`].
    pub(in crate::lookout::app) fn on_secrets_text_key(&mut self, key: KeyPress) -> Effect {
        match key {
            KeyPress::Quit => return Effect::Quit,
            KeyPress::TextChar(typed) => {
                if let Some(typing) = self
                    .secrets_pane_mut()
                    .and_then(|pane| pane.typing.as_mut())
                {
                    typing.buffer.insert(typed);
                }
            }
            KeyPress::TextBackspace => {
                if let Some(typing) = self
                    .secrets_pane_mut()
                    .and_then(|pane| pane.typing.as_mut())
                {
                    typing.buffer.backspace();
                }
            }
            KeyPress::TextEdit(edit) => {
                if let Some(typing) = self
                    .secrets_pane_mut()
                    .and_then(|pane| pane.typing.as_mut())
                {
                    typing.buffer.edit(edit);
                }
            }
            KeyPress::TextApply => return self.apply_secrets_text(),
            KeyPress::TextAbandon => {
                if let Some(pane) = self.secrets_pane_mut() {
                    pane.typing = None;
                }
                self.mode = InputMode::Normal;
            }
            _ => {}
        }
        Effect::None
    }

    /// `TextApply` on the secrets pane's own input.
    ///
    /// The name step hands straight to the value step rather than writing
    /// anything on its own. The value step validates against the store's
    /// own rules ([`shep_core::secrets::is_name`],
    /// [`shep_core::secrets::MAX_VALUE_BYTES`]) rather than a second copy of
    /// either, and raises [`Effect::WriteSecret`] only once both the
    /// grammar and the control gate hold; a refusal reopens the same input
    /// with what was typed still in it, so neither costs a retype.
    fn apply_secrets_text(&mut self) -> Effect {
        let Some(typing) = self.secrets_pane_mut().and_then(|pane| pane.typing.take()) else {
            return Effect::None;
        };
        match typing.what {
            TypingWhat::NewKey => {
                let name = typing.buffer;
                if shep_core::secrets::is_name(name.as_str()) {
                    if let Some(pane) = self.secrets_pane_mut() {
                        pane.typing = Some(Typing {
                            what: TypingWhat::ValueFor(name.as_str().to_string()),
                            buffer: TextBox::new(),
                        });
                    }
                    return Effect::None;
                }
                self.notice = Some(Notice::grave(format!(
                    "{:?} is not a valid key: {NEW_KEY_GRAMMAR}",
                    name.as_str()
                )));
                if let Some(pane) = self.secrets_pane_mut() {
                    pane.typing = Some(Typing {
                        what: TypingWhat::NewKey,
                        buffer: name,
                    });
                }
                Effect::None
            }
            TypingWhat::ValueFor(key) => {
                let value = typing.buffer;
                if value.as_str().len() > shep_core::secrets::MAX_VALUE_BYTES {
                    self.notice = Some(Notice::grave(format!(
                        "value is {} bytes, over the {}-byte limit",
                        value.as_str().len(),
                        shep_core::secrets::MAX_VALUE_BYTES
                    )));
                    if let Some(pane) = self.secrets_pane_mut() {
                        pane.typing = Some(Typing {
                            what: TypingWhat::ValueFor(key),
                            buffer: value,
                        });
                    }
                    return Effect::None;
                }
                // No tab showing is no environment to write to: the empty
                // name is a slot no tab reads. Unreachable through the
                // keymap today, since opening this input needs a loaded
                // model and a loaded model always carries `all`.
                let Some(environment) = (match &self.body {
                    Body::Secrets(pane) => pane.environment().map(str::to_string),
                    Body::FlockTable
                    | Body::Settings(_)
                    | Body::ConfigPane(_)
                    | Body::Bleats(_)
                    | Body::Sheep(_) => None,
                }) else {
                    // Refused the way the too-long refusal above is: the
                    // input stays open holding what was typed, so a tab
                    // that went away costs no retype.
                    if let Some(pane) = self.secrets_pane_mut() {
                        pane.typing = Some(Typing {
                            what: TypingWhat::ValueFor(key),
                            buffer: value,
                        });
                    }
                    return Effect::None;
                };
                let Some(authority) = self.authorize_write() else {
                    return Effect::None;
                };
                self.mode = InputMode::Normal;
                Effect::WriteSecret(
                    SecretEdit {
                        key,
                        environment,
                        value: Some(value.as_str().to_string()),
                    },
                    authority,
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    use super::super::testing::*;
    use crate::lookout::view::fixtures;

    #[test]
    fn enter_opens_the_value_input_seeded_empty() {
        let mut app = fixtures::app_with_secrets_and_control();

        let _ = app.update(Msg::Key(KeyPress::Confirm));

        let typing = typing_of(&app).expect("the input is open");
        assert_eq!(typing.what, TypingWhat::ValueFor("DB_PASSWORD".into()));
        assert_eq!(
            typing.buffer.as_str(),
            "",
            "seeding it with the stored value would put a secret on screen \
                 that `v` and its gate exist to control"
        );
    }

    #[test]
    fn a_write_refuses_without_the_control_gate() {
        let mut app = fixtures::app_with_secrets_read_only();

        let _ = app.update(Msg::Key(KeyPress::Confirm));

        assert!(typing_of(&app).is_none());
        assert!(
            notice_of(&app).is_some_and(|n| n.contains("read-only")),
            "the existing refusal, not a second one"
        );
    }

    #[test]
    fn a_value_over_the_cap_is_refused_at_the_input_not_at_the_file() {
        let mut app = fixtures::app_typing_a_value();
        for _ in 0..=shep_core::secrets::MAX_VALUE_BYTES {
            let _ = app.update(Msg::Key(KeyPress::TextChar('x')));
        }

        let effect = app.update(Msg::Key(KeyPress::TextApply));

        assert!(matches!(effect, Effect::None), "nothing reached the file");
        assert!(notice_of(&app).is_some_and(|n| n.contains("4096")));
    }

    #[test]
    fn a_key_outside_the_grammar_is_refused_with_the_grammar() {
        let mut app = fixtures::app_typing_a_new_key();
        for c in ".bad".chars() {
            let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
        }

        let effect = app.update(Msg::Key(KeyPress::TextApply));

        assert!(matches!(effect, Effect::None));
        assert!(
            notice_of(&app).is_some_and(|n| n.contains("not starting with a dot")),
            "the refusal states the rule, not just that it failed"
        );
    }

    #[test]
    fn a_value_lands_in_the_tabs_own_environment() {
        let mut app = fixtures::app_with_secrets_and_control();
        let _ = app.update(Msg::Key(KeyPress::TabNext));
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        for c in "s3cret".chars() {
            let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
        }

        let effect = app.update(Msg::Key(KeyPress::TextApply));

        let Effect::WriteSecret(edit, _) = effect else {
            panic!("expected a write, got {effect:?}");
        };
        assert_eq!(edit.environment, second_tab_of(&app));
        assert_eq!(edit.value.as_deref(), Some("s3cret"));
    }

    /// A reload's environment union can shrink while a value input is open,
    /// and `SecretsPane::environment` over an empty list names no tab. The
    /// write refuses rather than naming the environment `""`.
    #[test]
    fn a_value_with_no_environment_tab_writes_nothing() {
        let mut app = fixtures::app_typing_a_value();
        let _ = app.update(Msg::Secrets {
            environment: "all".to_string(),
            result: Ok(Box::default()),
        });
        assert!(
            typing_of(&app)
                .is_some_and(|typing| typing.what == TypingWhat::ValueFor("DB_PASSWORD".into())),
            "sanity: the input outlived the load that took every tab away"
        );

        for c in "s3cret".chars() {
            let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
        }
        let effect = app.update(Msg::Key(KeyPress::TextApply));

        assert!(
            !matches!(effect, Effect::WriteSecret(..)),
            "no tab is showing, so nothing here names an environment to write to: {effect:?}"
        );
        assert!(matches!(effect, Effect::None));
        assert!(
            notice_of(&app).is_none(),
            "silent, the way a missing tab refuses a reveal and a delete"
        );
        assert_eq!(
            typing_of(&app).map(|typing| (typing.what.clone(), typing.buffer.as_str().to_string())),
            Some((
                TypingWhat::ValueFor("DB_PASSWORD".into()),
                "s3cret".to_string()
            )),
            "the refusal keeps what was typed, the way the too-long one does"
        );
        assert_eq!(
            app.mode(),
            InputMode::Text,
            "and the input is still the live one, not a copy off the screen"
        );
    }

    #[test]
    fn a_successful_write_takes_a_revealed_value_off_the_screen() {
        let mut app = fixtures::app_revealing_with_control();

        let _ = app.update(Msg::SecretWritten { result: Ok(true) });

        assert!(
            reveal_of(&app).is_none(),
            "the value on screen belonged to what the store held before the write"
        );
    }

    #[test]
    fn a_failed_write_says_why_and_leaves_the_table_alone() {
        let mut app = fixtures::app_with_secrets_and_control();
        let before = row_count(&app);

        let _ = app.update(Msg::SecretWritten {
            result: Err("permission denied (os error 13)".to_string()),
        });

        assert!(
            notice_of(&app).is_some_and(|n| n.contains("permission denied")),
            "the operator gets the reason, not a silent no-op"
        );
        assert_eq!(row_count(&app), before, "and nothing is redrawn as changed");
    }

    #[test]
    fn the_new_key_row_opens_a_name_input_and_then_a_value_input() {
        let mut app = fixtures::app_with_secrets_and_control();
        select_new_key_row(&mut app);

        let _ = app.update(Msg::Key(KeyPress::Confirm));
        assert_eq!(
            typing_of(&app).map(|t| t.what.clone()),
            Some(TypingWhat::NewKey)
        );

        for c in "NEW_KEY".chars() {
            let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
        }
        let effect = app.update(Msg::Key(KeyPress::TextApply));

        assert!(
            matches!(effect, Effect::None),
            "naming a key writes nothing on its own"
        );
        assert_eq!(
            typing_of(&app).map(|t| t.what.clone()),
            Some(TypingWhat::ValueFor("NEW_KEY".into())),
            "the name input hands straight over to the value input"
        );
    }

    #[test]
    fn a_provider_row_refuses_a_write() {
        let mut app = fixtures::app_with_a_pushed_secret_selected_and_control();

        let _ = app.update(Msg::Key(KeyPress::Confirm));

        assert!(typing_of(&app).is_none());
        assert!(
            notice_of(&app).is_some_and(|n| n.contains("pushed by a dog")),
            "and it says why rather than doing nothing"
        );
    }

    /// A pasted secret goes through the same box as a typed one, and nothing
    /// that prints a message or a `Debug` carries it.
    #[test]
    fn a_pasted_value_is_never_printed_in_a_notice_or_a_debug() {
        let mut app = fixtures::app_typing_a_value();
        let paste = Msg::Paste(Pasted::new("hunter2\nsecond".to_string()));

        assert_eq!(format!("{paste:?}"), "Paste(Pasted(<14 bytes>))");
        let _ = app.update(paste);

        let typing = typing_of(&app).expect("the newline did not apply the input");
        assert_eq!(typing.buffer.as_str(), "hunter2second");
        assert_eq!(
            format!("{typing:?}"),
            "Typing { what: ValueFor(\"DB_PASSWORD\"), buffer: <13 bytes> }"
        );
        assert_eq!(notice_of(&app), None);
    }

    /// The cursor keys edit a secret in the middle too.
    #[test]
    fn a_secret_value_can_be_corrected_at_the_cursor() {
        let mut app = fixtures::app_typing_a_value();
        for typed in "xz".chars() {
            let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
        }
        let _ = app.update(Msg::Key(KeyPress::TextEdit(TextEdit::Left)));
        let _ = app.update(Msg::Key(KeyPress::TextChar('y')));

        assert_eq!(typing_of(&app).unwrap().buffer.as_str(), "xyz");
    }
}