shep 0.15.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! `shep serve`: registers a static file server as a managed sheep, or,
//! with `--foreground`, runs the worker directly in this terminal.
//!
//! [`serve`] does both halves, and every refusal and notice before either:
//! the registered sheep is this same binary re-invoked with `--foreground`
//! ([`sheep_args`]), so the shepherd's spawn of it runs back through here
//! and re-derives them against its own stderr, where `shep bleats` reads.
//!
//! Dispatched from `lib.rs` ahead of the shared `$SHEP_HOME`-gated, locked
//! block: `--foreground` runs until signalled, and a `StdoutLock` held for
//! a process lifetime wedges the first off-thread write elsewhere.

use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};

use shep_client::START_DEADLINE;
use shep_core::config::AppConfig;
use shep_core::paths::ShepPaths;
use shep_core::protocol::{Request, Response};

use crate::cli::ServeArgs;
use crate::commands::rpc::request_and_render;
use crate::exit::ExitCode;
use crate::output::{FlockRows, Streams};
use crate::serve::auth::{self, AuthError, Credentials};
use crate::serve::worker::{self, ServeConfig};

/// Why the shared refusals stopped an invocation before either half ran.
#[derive(Debug)]
enum ServeRefusal {
    /// `root` does not exist, or a component along the way is not itself a
    /// directory. Carries `std::fs::canonicalize`'s own error.
    RootUnresolvable {
        /// The path as the operator wrote it.
        root: PathBuf,
        /// The underlying IO failure.
        source: std::io::Error,
    },
    /// `root` resolved to a real path that is not a directory.
    RootNotADirectory {
        /// The resolved, canonical path.
        root: PathBuf,
    },
    /// `--auth` named a file [`auth::load`] refused, or that could not be
    /// canonicalized after loading fine.
    Auth(AuthError),
    /// `--spa` was given but `root` holds no `index.html` to answer a 404
    /// with.
    MissingSpaIndex {
        /// The resolved, canonical docroot.
        root: PathBuf,
    },
}

impl std::fmt::Display for ServeRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::RootUnresolvable { root, source } => write!(f, "{}: {source}", root.display()),
            Self::RootNotADirectory { root } => write!(f, "{}: not a directory", root.display()),
            Self::Auth(err) => write!(f, "{err}"),
            Self::MissingSpaIndex { root } => write!(
                f,
                "--spa was given but {} has no index.html",
                root.display()
            ),
        }
    }
}

impl core::error::Error for ServeRefusal {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::RootUnresolvable { source, .. } => Some(source),
            Self::RootNotADirectory { .. } | Self::MissingSpaIndex { .. } => None,
            Self::Auth(err) => Some(err),
        }
    }
}

impl From<AuthError> for ServeRefusal {
    fn from(source: AuthError) -> Self {
        Self::Auth(source)
    }
}

/// The exit code a [`ServeRefusal`] reports: a bad `root` is a usage error,
/// a bad `--auth` file or a missing SPA index a config error.
fn refusal_exit_code(refusal: &ServeRefusal) -> ExitCode {
    match refusal {
        ServeRefusal::RootUnresolvable { .. } | ServeRefusal::RootNotADirectory { .. } => {
            ExitCode::Usage
        }
        ServeRefusal::Auth(_) | ServeRefusal::MissingSpaIndex { .. } => ExitCode::InvalidConfig,
    }
}

/// Renders `refusal` and returns the exit code it reports.
fn fail(streams: &mut Streams<'_>, refusal: &ServeRefusal) -> ExitCode {
    let code = refusal_exit_code(refusal);
    streams.fail(code, &refusal.to_string())
}

/// Resolves and canonicalizes `root`, refusing it if it is missing or not a
/// directory.
fn validate_root(root: &Path) -> Result<PathBuf, ServeRefusal> {
    let canonical =
        std::fs::canonicalize(root).map_err(|source| ServeRefusal::RootUnresolvable {
            root: root.to_path_buf(),
            source,
        })?;
    if canonical.is_dir() {
        Ok(canonical)
    } else {
        Err(ServeRefusal::RootNotADirectory { root: canonical })
    }
}

/// Loads and canonicalizes `path` as `--auth`'s creds file, if given.
///
/// Canonicalizing here, not in [`sheep_args`]: a relative `--auth` baked
/// into the registered command line resolves against the shepherd's cwd,
/// giving a sheep that registers clean and crash-loops on its first spawn.
///
/// # Errors
/// [`ServeRefusal::Auth`] if the file cannot be loaded or, having loaded,
/// cannot be canonicalized.
fn validate_auth(path: &Path) -> Result<(PathBuf, Credentials), ServeRefusal> {
    let credentials = auth::load(path)?;
    let canonical = std::fs::canonicalize(path).map_err(|source| {
        ServeRefusal::Auth(AuthError::Io {
            path: path.to_path_buf(),
            source,
        })
    })?;
    Ok((canonical, credentials))
}

/// The compensating control for allowing `--bind` wider than loopback
///
/// `None` when `bind` is loopback; otherwise a stderr notice naming the
/// address and the docroot, and, when no `--auth` was set, saying its files
/// are readable by anything that can reach the port.
fn exposure_notice(bind: IpAddr, auth: bool, root: &Path) -> Option<String> {
    if bind.is_loopback() {
        return None;
    }
    let root = root.display();
    Some(if auth {
        format!(
            "shep serve: bound to {bind}, reachable from beyond this host. {root} is exposed \
             to anything that can reach the port"
        )
    } else {
        format!(
            "shep serve: bound to {bind}, reachable from beyond this host, with no --auth set. \
             {root}'s files will be readable by anything that can reach the port"
        )
    })
}

/// A stderr notice naming the check-then-open race `--follow-symlinks`
/// reopens, or `None` when the flag is off
///
/// Independent of [`exposure_notice`]: a loopback serve with the flag on
/// still needs this one.
fn follow_symlinks_notice(follow_symlinks: bool) -> Option<String> {
    if !follow_symlinks {
        return None;
    }
    Some(
        "shep serve: --follow-symlinks reopens the check-then-open race (TOCTOU) the default \
         per-component walk closes. A symlink under the docroot can now point anywhere this \
         process can read"
            .to_string(),
    )
}

/// The sheep's own command line, rebuilt from the flags rather than from
/// `std::env::args`
///
/// The operator's cwd is not the shepherd's, and one canonical flag order
/// makes `shep describe` show the same line however it was typed. `root`
/// and `auth` must both arrive canonical; this only emits what it is
/// handed. `--name` and `--fold` are registration-time facts and stay out.
/// Every worker-time flag goes in, `--follow-symlinks` included: a restart
/// that dropped it would silently change what the worker serves.
fn sheep_args(root: &Path, auth: Option<&Path>, args: &ServeArgs) -> Vec<String> {
    let mut out = vec!["serve".to_string(), root.display().to_string()];
    out.push("--port".to_string());
    out.push(args.port.to_string());
    out.push("--bind".to_string());
    out.push(args.bind.to_string());
    if args.spa {
        out.push("--spa".to_string());
    }
    if args.listing {
        out.push("--listing".to_string());
    }
    if args.hidden {
        out.push("--hidden".to_string());
    }
    if args.follow_symlinks {
        out.push("--follow-symlinks".to_string());
    }
    if let Some(auth) = auth {
        out.push("--auth".to_string());
        out.push(auth.display().to_string());
    }
    out.push("--foreground".to_string());
    out
}

/// The name a registered sheep gets when `--name` is absent: the canonical
/// docroot's own file name, falling back to `serve` when it has none (`/`,
/// or a root the platform gives no basename to).
fn default_name(root: &Path) -> String {
    root.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| "serve".to_string())
}

/// `shep serve`'s entry point, reached from `lib.rs`'s early dispatch
///
/// Does every refusal and every notice once, for both halves, so
/// `--foreground` and the registered sheep cannot disagree about what is
/// valid.
pub async fn serve(streams: &mut Streams<'_>, paths: &ShepPaths, args: &ServeArgs) -> ExitCode {
    let root = match validate_root(&args.root) {
        Ok(root) => root,
        Err(refusal) => return fail(streams, &refusal),
    };

    let auth = match args.auth.as_deref() {
        Some(path) => match validate_auth(path) {
            Ok(auth) => Some(auth),
            Err(refusal) => return fail(streams, &refusal),
        },
        None => None,
    };

    if args.spa && !root.join("index.html").is_file() {
        return fail(streams, &ServeRefusal::MissingSpaIndex { root });
    }

    if let Some(notice) = exposure_notice(args.bind, auth.is_some(), &root) {
        streams.aside("exposure", &notice);
    }
    if let Some(notice) = follow_symlinks_notice(args.follow_symlinks) {
        streams.aside("follow_symlinks", &notice);
    }

    if args.foreground {
        let cfg = ServeConfig {
            root,
            bind: SocketAddr::new(args.bind, args.port),
            spa: args.spa,
            listing: args.listing,
            hidden: args.hidden,
            auth: auth.map(|(_, credentials)| credentials),
            follow_symlinks: args.follow_symlinks,
            connection_deadline: worker::CONNECTION_DEADLINE,
        };
        return worker::run(cfg).await;
    }

    register(
        streams,
        paths,
        &root,
        auth.as_ref().map(|(path, _)| path.as_path()),
        args,
    )
    .await
}

/// Registers `root` as a sheep whose command line runs this same binary
/// again with `--foreground` appended ([`sheep_args`]), through the
/// `connect_or_spawn_client` path `shep start` uses.
async fn register(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    root: &Path,
    auth: Option<&Path>,
    args: &ServeArgs,
) -> ExitCode {
    let exe = match std::env::current_exe() {
        Ok(exe) => exe,
        Err(source) => {
            let message = format!("could not resolve this binary's own path: {source}");
            return streams.fail(ExitCode::Failure, &message);
        }
    };

    let name = args.name.clone().unwrap_or_else(|| default_name(root));
    let mut app = AppConfig::minimal(&name, &exe.display().to_string());
    app.args = sheep_args(root, auth, args);
    app.fold.clone_from(&args.fold);

    // `serve` registers a sheep, so it is not one of
    // `crate::RECOVERY_VERBS` and there is no value but `Enforce` here.
    let client = match crate::client::connect_or_spawn_client(
        streams,
        paths,
        crate::version_guard::VersionGuard::Enforce,
    )
    .await
    {
        Ok(client) => client,
        Err(code) => return code,
    };

    request_and_render(
        &client,
        streams,
        "serve",
        Request::Start { apps: vec![app] },
        Some(START_DEADLINE),
        |response| match response {
            Response::Started(procs) => Some(FlockRows(procs)),
            _ => None,
        },
    )
    .await
}

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

    fn full_args() -> ServeArgs {
        ServeArgs {
            root: PathBuf::from("./dist"),
            port: 9000,
            bind: "0.0.0.0".parse().unwrap(),
            name: Some("web".into()),
            fold: Some("prod".into()),
            spa: true,
            listing: true,
            hidden: true,
            follow_symlinks: true,
            auth: Some(PathBuf::from("./creds")),
            foreground: false,
        }
    }

    /// Every field of `ServeArgs` is non-default here, so a forgotten flag
    /// shows up as an absence rather than a matching default.
    #[test]
    fn the_registered_command_line_is_absolute_and_carries_every_flag() {
        let args = full_args();
        let built = sheep_args(Path::new("/srv/www"), Some(Path::new("/srv/creds")), &args);
        assert_eq!(built[0], "serve");
        assert_eq!(built[1], "/srv/www");
        assert!(built.contains(&"--foreground".to_string()));
        assert!(built.contains(&"--spa".to_string()));
        assert!(built.contains(&"--listing".to_string()));
        assert!(built.contains(&"--hidden".to_string()));
        assert!(
            built.contains(&"--follow-symlinks".to_string()),
            "a sheep that quietly drops this on restart silently reopens the safe default"
        );
        assert!(built.windows(2).any(|w| w == ["--port", "9000"]));
        assert!(
            built.windows(2).any(|w| w == ["--bind", "0.0.0.0"]),
            "a sheep that quietly binds loopback is a silent downgrade"
        );
        assert!(
            built.windows(2).any(|w| w == ["--auth", "/srv/creds"]),
            "absolute, or the sheep crash-loops after a green registration"
        );
        assert!(
            !built.contains(&"--name".to_string()),
            "registration-time only"
        );
        assert!(
            !built.contains(&"--fold".to_string()),
            "registration-time only"
        );
    }

    /// Whole-struct equality, not field by field: a field added to
    /// `ServeArgs` with no matching arm in `sheep_args` then fails by
    /// construction.
    #[test]
    fn the_registered_command_line_parses_back_to_the_same_arguments() {
        use crate::cli::{Cli, Commands};
        use clap::Parser;

        let original = full_args();
        let built = sheep_args(
            Path::new("/srv/www"),
            Some(Path::new("/srv/creds")),
            &original,
        );
        let mut argv = vec!["shep".to_string()];
        argv.extend(built);
        let cli = Cli::try_parse_from(argv).expect("the line shep registers must parse");
        let Commands::Serve(parsed) = cli.command else {
            panic!("expected serve")
        };
        assert_eq!(
            parsed,
            ServeArgs {
                root: PathBuf::from("/srv/www"),
                auth: Some(PathBuf::from("/srv/creds")),
                foreground: true,
                // registration-time only
                name: None,
                fold: None,
                ..original
            }
        );
    }

    /// The notice is the whole compensating control for `--bind 0.0.0.0`.
    #[test]
    fn a_non_loopback_bind_produces_a_notice_that_names_the_address() {
        use std::net::{IpAddr, Ipv4Addr};
        assert!(
            exposure_notice(
                IpAddr::V4(Ipv4Addr::LOCALHOST),
                false,
                Path::new("/srv/www")
            )
            .is_none()
        );
        let notice = exposure_notice("0.0.0.0".parse().unwrap(), false, Path::new("/srv/www"))
            .expect("a wider bind must say so");
        assert!(notice.contains("0.0.0.0"), "{notice}");
        assert!(notice.contains("/srv/www"), "{notice}");
        assert!(
            notice.contains("readable"),
            "no auth: say what that means: {notice}"
        );
        let with_auth = exposure_notice("0.0.0.0".parse().unwrap(), true, Path::new("/srv/www"))
            .expect("still a wider bind");
        assert!(!with_auth.contains("readable"), "{with_auth}");
    }

    #[test]
    fn follow_symlinks_produces_a_notice_that_names_the_race() {
        assert!(follow_symlinks_notice(false).is_none());
        let notice = follow_symlinks_notice(true).expect("the flag must say so");
        assert!(notice.contains("--follow-symlinks"), "{notice}");
        assert!(
            notice.contains("race") || notice.contains("TOCTOU"),
            "{notice}"
        );
    }
}