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
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
//! Spawn seam between the daemon engine and the OS
//!
//! [`ProcessRunner`] spawns a child; the [`RunningProcess`] it returns owns
//! that one live child for its whole lifetime (pid, wait, signal, kill).
//! Spawn also hands back a [`ProcIo`] bundle of channels so the owning sheep
//! task can pump stdout/stderr lines and shepherd-channel messages without
//! the runner itself blocking on delivery.
//!
//! Two implementations exist: a deterministic scripted fake (this crate's
//! test-only `fake` module, `ScriptedRunner`) for engine tests, and a real
//! runner over OS processes (a later task) for production.
//!
//! It also owns the log plane's shared vocabulary — [`LogCtl`] and the two
//! errors its requests answer with — and, with them, this crate's only
//! opener of a sheep's log file (`open_log_path`, crate-private) plus the
//! ancestry guard that runs ahead of it. The log pump and `shep flush` both
//! go through that pair, so neither half can drift from the other on what it
//! is willing to open.
//!
//! This whole module is public and stays that way: [`ProcessRunner`] is the
//! bound on [`boot`](crate::boot::boot), which `shep-cli` calls, so a caller
//! outside this crate has to be able to name it — and naming it drags in every
//! type in its signature. `tests/real_runner.rs` drives the same surface
//! directly against real children.
use fmt;
use BTreeMap;
use io;
use ;
use ;
use OperatorSignal;
use crate;
use crateCredentials;
/// One exit observation
/// Typed stop signal
///
/// [`StopSignal::as_raw`] gives the unix number so fake and real runners
/// record identical [`ExitOutcome`]s.
/// One stdout/stderr line from a child
/// What the supervisor can ask a log pump to do mid-flight.
///
/// # Why a pushed message rather than a generation counter
///
/// A counter the pump re-read before each write would only ever promise
/// "before the next line", and **a quiet sheep never writes a next line** —
/// so a caller could ask for a rotation, or for the pending writes to land,
/// and be told nothing about when or whether the daemon caught up. The
/// [`oneshot`] on each variant below is the whole point of the shape: once it
/// resolves, every live pump has provably done the thing, which is what makes
/// either variant usable as a barrier. A logrotate `postrotate` stanza needs
/// that of [`Self::Reopen`] before it compresses or deletes the file it
/// renamed; `shep flush` needs it of [`Self::Flush`] before it truncates.
/// A [`LogCtl::Reopen`] that could not open one or both of a sheep's log
/// files again.
///
/// Carries a rendered message rather than the `io::Error`s behind it, the
/// same way [`RunnerError`] does: it crosses a channel, ends up in an RPC
/// error message, and every layer between only ever prints it. Keeping it a
/// `String` is also what keeps this `Clone`/`Eq`, which `io::Error` is not.
/// A `shep flush` that could not empty a log file, from either of the two
/// halves that verb is made of: a pump whose pending writes would not reach
/// the file ([`LogCtl::Flush`]), or a path that could not be truncated once
/// they had.
///
/// One type for both halves because an operator is owed one answer about one
/// file, and because either half failing costs them the same non-zero exit.
/// What it leaves behind differs, and this type says nothing about which: a
/// truncate that failed leaves its file as it was, while a flush that failed
/// does not hold up the truncate — the bytes it reports are bytes that
/// errored, not bytes still in flight — so that file does end up empty and
/// the lines it held are gone unwritten. Carries a rendered message for the
/// reasons [`ReopenError`] gives.
/// What an operator is told when a log path turns out to be a symlink.
///
/// One owner for the sentence, cited by [`open_log_path`]'s doc and by both
/// openers' tests: an operator who legitimately keeps `/var/log/app` as a
/// symlink to another filesystem reads this, not a bare `ELOOP`, and the
/// remedy is in the sentence itself. The path is NOT in here — every caller
/// already prefixes one (`"<path>: <what the open reported>"`, see
/// [`ReopenError::message`] and [`FlushError::message`]), and repeating it
/// would print it twice.
pub const SYMLINK_REFUSED: &str = "refusing to follow a symlink at this log path; shep \
opens log files with O_NOFOLLOW, so point out_file/err_file at the real file";
/// Opens `path` through `options`, refusing to follow a symlink standing at
/// the path itself.
///
/// The one opener of a log file in this crate, in both directions: the log
/// pump's append handle (`tokio_runner`'s `open_append`) and `shep flush`'s
/// truncating one (`supervisor`'s `truncate_log`) both come through here, so
/// the two halves of the log plane cannot drift on what they will open.
///
/// [`check_log_ancestry`] is this function's other half and runs BEFORE it at
/// both call sites — before `open_append`'s `mkdir` in particular, so no
/// directory is created down an ancestry that is about to be refused. The two
/// are split rather than nested for exactly that ordering; neither is
/// meaningful without the other.
///
/// # Security
///
/// An app's `out_file`/`err_file` are free-form config the assembler takes
/// verbatim, so a log path can name anywhere the daemon can write. Under a
/// root daemon that turns a pre-existing loose directory into a
/// write-and-truncate primitive: another local user plants a symlink where
/// the log file will be, the pump appends through it, and `shep flush`
/// empties whatever it points at. `O_NOFOLLOW` closes that: the open fails
/// with `ELOOP` instead, the symlink is left alone, and its target is
/// untouched.
///
/// What it does NOT cover, stated plainly because the gap is real:
/// `O_NOFOLLOW` guards only the FINAL path component. A symlinked *parent*
/// directory still resolves, so `logs -> /elsewhere` followed by
/// `logs/app.log` reaches `/elsewhere/app.log` exactly as before. Closing
/// that in the open itself needs `openat2(RESOLVE_NO_SYMLINKS)`, which is
/// Linux-only — so it cannot be the only path here, though it could be a
/// Linux fast path beside this one. What that would cost, and why Phase 10
/// did not spend it, is on [`check_log_ancestry`] and in
/// `docs/specs/deferred.md`. [`check_log_ancestry`] covers that case from the
/// other side — by refusing an ancestry a privileged daemon should not be
/// writing below at all — but it checks rather than resolves, so a TOCTOU
/// window remains between the two. This stops the realistic attack; it does
/// not make the operation atomic.
///
/// `custom_flags` is safe, so none of this is the exception to
/// `shep-daemon/src/sys.rs` owning every `unsafe` block in this crate
/// (IR-22).
///
/// # Errors
///
/// Whatever the open reported. An `ELOOP` — the refusal above — is relabelled
/// to [`SYMLINK_REFUSED`] on the way out, because `ELOOP`'s own strerror
/// ("too many levels of symbolic links") reads as a symlink *loop* and tells
/// an operator with one perfectly ordinary symlink neither what shep did nor
/// what to change. Every other error is passed through untouched, `NotFound`
/// included — `truncate_log` still recognises it.
pub async
/// Relabels the `ELOOP` an `O_NOFOLLOW` open answers with, leaving every
/// other error exactly as the OS reported it.
///
/// Both platforms shep supports report the refusal the same way — POSIX
/// specifies `ELOOP`, and Darwin's `open(2)` matches it (measured, not
/// assumed) — so one errno covers the tier rather than a per-platform list.
/// The kind is carried over rather than invented: only the message changes.
/// The non-unix arm of [`name_the_symlink`]: there is no `O_NOFOLLOW` to
/// apply on this tier, so there is no refusal to relabel either.
/// Refuses — under a privileged shepherd — to open a log file whose ancestry
/// another local user could redirect, and warns about it under any other.
///
/// [`open_log_path`]'s other half, run before it (and before any `mkdir`) at
/// both of that function's call sites.
///
/// # Why the split by uid
///
/// The chain is an ESCALATION only when the daemon is privileged. A shepherd
/// running as an ordinary user that logs into a shared directory has handed
/// nobody anything they could not already do as themselves — it is a footgun,
/// not a vulnerability — and refusing it outright would break a developer
/// logging to `/tmp`, which is a legitimate thing to do. So root refuses and
/// everyone else is warned, once per path. The warning costs nothing at the
/// default level: the subscriber ships at `warn`.
///
/// # What counts as loose
///
/// See [`loose_ancestor`]. Two things, both about the components of the path
/// itself rather than about where it points: an ancestor owned by neither the
/// daemon's uid nor root, and a world-writable ancestor DIRECTORY. Ownership
/// is the load-bearing half — it is what catches an intermediate component
/// swapped for a symlink, which `O_NOFOLLOW` on the final component cannot
/// see, and it catches a plain `0755` directory owned by the app's own
/// dropped-privilege user, which the write bit alone would wave through.
///
/// # What remains
///
/// A TOCTOU window. This checks the ancestry and then opens the path with no
/// atomic tie between the two, so an attacker who can rearrange a directory
/// between the check and the open still wins that race. The bar is raised
/// substantially; the operation is not atomic.
///
/// The syscall that would close it on Linux is
/// `openat2(RESOLVE_NO_SYMLINKS)`, and it IS reachable — `nix 0.29` exposes
/// `fcntl::openat2` under the `fs` feature this crate already enables. What
/// stops it being a Linux fast path here is not availability but cost:
/// `openat2` hands back a `RawFd`, so adopting it into a `File` needs
/// `FromRawFd`, which is `unsafe` and belongs in `sys.rs` (IR-22), behind a
/// `cfg(target_os = "linux")` with an `ENOSYS`/`EPERM` fallback ladder for
/// pre-5.6 kernels and seccomp sandboxes — new unsafe on a Linux-only path
/// this project cannot execute a test for from a macOS development machine.
/// The design is written down in `docs/specs/deferred.md` rather than
/// half-built here.
///
/// # Errors
///
/// [`io::ErrorKind::PermissionDenied`], naming the offending ancestor and
/// why, when the daemon's effective uid is root and an ancestor is loose. The
/// message carries no path of its own — every caller prefixes the log path
/// already.
pub
/// The effective uid a shepherd has to be running as for a loose ancestor to
/// be an escalation rather than a footgun.
const ROOT_UID: u32 = 0;
/// The permission bit that lets every local user create entries in a
/// directory. Narrower on purpose than `boot`'s socket-directory check, which
/// tests `0o022` (group OR world): a group-writable log directory names a
/// specific set of accounts an operator chose, while this bit names everyone.
const WORLD_WRITABLE: u32 = 0o002;
/// Log paths whose loose ancestry has already been reported, so an
/// unprivileged shepherd says it once rather than on every respawn, every
/// reopen and every flush of the same file.
///
/// Keyed by the LOG path, not by the offending ancestor: the warning names
/// both, and an operator asking "which of my apps is this about?" is asking
/// about the one this set is keyed on. Bounded by the number of distinct log
/// paths in the flock.
static WARNED_LOOSE_LOG_PATHS: LazyLock = new;
/// [`check_log_ancestry`] with the daemon's effective uid supplied, so the
/// privileged arm is reachable from a test that is not running as root.
///
/// # Errors
///
/// [`check_log_ancestry`]'s.
/// An ancestor of a log path that another local user could use to redirect
/// where that path lands.
/// Why an ancestor of a log path counts as loose.
/// The nearest ancestor of `path` that another local user could use to
/// redirect it, or `None` when every one of them is already the daemon's to
/// trust.
///
/// Walks the path's own textual components from its parent upwards and stops
/// at the first offender, so the ancestor reported is the one closest to the
/// log file — the one an operator can actually do something about, and the
/// one a test can pin without knowing what `/tmp` looks like on the runner.
///
/// `symlink_metadata`, never `metadata`: a symlinked component must be read
/// as the link it is (owned by whoever planted it) rather than as whatever it
/// resolves to. That is the whole reason ownership is checked at all —
/// `O_NOFOLLOW` on the final component cannot see a redirect one level up.
///
/// An ancestor that does not exist is skipped rather than trusted or blamed:
/// `open_append` is about to create it, and every directory shep creates it
/// creates at `boot::DIR_MODE` (`0700`) as the daemon's own user, which is
/// exactly what this function would then wave through. An ancestor that
/// cannot be stat'd at all is skipped for the same reason it cannot be
/// judged.
///
/// # Cost
///
/// One `lstat(2)` per component of the path, once per log-file open — so
/// every spawn, every respawn, every reopen, and once per distinct path in a
/// flush. The syscalls hit the kernel's dentry cache after the first, and the
/// walk stops early on the first offender, which on a loose ancestry is
/// usually the first component it looks at.
///
/// Measured on macOS (release, warm cache, no offender so the walk runs to
/// the root): **7.8 µs** for a nine-component path — the shape
/// `$SHEP_HOME/logs/<name>-<n>-out.log` has under a home directory — and
/// **26 µs** for a twenty-four-component one, so about 1.1 µs per component.
/// That is against an `open(2)` this crate already dispatches to the blocking
/// pool, and against the process spawn a pump's first open belongs to, which
/// costs milliseconds. It is run inline rather than on the blocking pool
/// because a few microseconds is well inside what a runtime worker may do
/// between yields, and a `spawn_blocking` hop per open would cost more than
/// the walk.
/// IO endpoints handed back by spawn — the runner pumps internally.
///
/// The sheep task owns this and MUST drain every receiver: an undrained
/// `from_child` back-pressures a metric-emitting child until it stalls on
/// its own fd-3 write (see the supervisor's `select!` model, a later task).
/// One line to write to a sheep's stdin, and where the answer goes.
///
/// The acknowledgement is the point, exactly as it is on [`LogCtl`]: an
/// `mpsc::send` only proves the message was queued, and a caller told "sent"
/// on that basis would be told it about a line still sitting in a channel
/// behind a pipe the app has stopped reading. The `oneshot` fires after the
/// bytes are written AND flushed, which is the strongest claim this side of
/// the pipe can honestly make.
/// A live child.
/// Spawn seam between engine and OS
/// What a [`ProcessRunner`] can tell about a [`SpawnSpec`] before anything is
/// spawned
///
/// Three variants because a caller registering a BATCH has three different
/// things to do with the answer, and collapsing any two of them costs a
/// flock. The line that matters runs between [`Self::Impossible`] and
/// [`Self::Doubtful`], and it is a line between two kinds of claim rather
/// than between two confidence levels:
///
/// - a path with a `/` in it is a claim about the FILESYSTEM, which the
/// daemon can check with certainty and an operator can fix with a typo
/// correction.
/// - a bare command is a claim about an ENVIRONMENT, and the environment
/// that matters is the daemon's, not the shell the operator tested in. A
/// `shep startup` unit gives the shepherd whatever `PATH` launchd or
/// systemd hands it, so `node` from homebrew on Apple Silicon
/// (`/opt/homebrew/bin`) and `node` from nvm (under `$HOME`) both resolve
/// in a terminal and neither resolves under the unit.
///
/// Refusing a batch on the second kind would mean one app's interpreter
/// keeping the other twelve down at boot, which is strictly worse than the
/// partial registration the check exists to prevent.
// `#[non_exhaustive]`: shep-daemon is a published library, an out-of-tree
// consumer can match this exhaustively today, and a fourth verdict would
// break them with no version bump to say so (IR-20).
/// Everything a spawn needs, pre-assembled by the assembler (a later task)
/// Error type returned from spawn and process control
///
/// `#[non_exhaustive]`: today's three variants cover spawn, signal delivery
/// and a stdin write, and a future process-control primitive — a cgroup
/// freeze, or a Windows job-object failure — would need its own variant
/// rather than stretching one of these to mean something it does not cover,
/// and shep-daemon is a published library an out-of-tree matcher should not
/// break for (IR-20).
// Every case here is `#[cfg(unix)]`, as is everything they exercise: the uid
// model `loose_ancestor` reads, the mode bits it tests, and
// `std::os::unix::fs::symlink`. On Windows this module compiles to nothing,
// which matches `check_log_ancestry`'s own non-unix arm having nothing to do.