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
//! Running the release's own build, as the target sheep's user and primary
//! group, and salvaging whatever it produced outside the release.
//!
//! **This is the dangerous step in the whole design.** Every other module
//! here reads a repository or shells out to `git`; this one executes
//! arbitrary code from it. `bun install`'s postinstall scripts are the
//! single most common supply-chain vector in the Node ecosystem, and
//! `make build` is arbitrary by construction - there is no way to make
//! running someone else's build script safe, only ways to bound the damage
//! when it turns out to be malicious. [`run`] is that bound, and how much of
//! a bound it is depends entirely on one field.
//!
//! ## The privilege drop happens only when the app sets `user`
//!
//! **With `user` set**, the build runs as that user's uid, primary gid and
//! nothing else: none of the shepherd's own privilege survives into it. Uid
//! alone would not be enough - the design spec recommends running the
//! shepherd as root specifically so it can drop privileges, and a child that
//! only dropped uid would keep root's own gid for the whole build - see
//! [`run`]'s own doc for the detail.
//!
//! **With `user` unset, which is the default, there is no drop at all.** The
//! build runs as whatever the shepherd runs as. Where the shepherd is root -
//! the arrangement its own docs recommend, precisely so that it CAN drop
//! privileges - a repository's `bun install` postinstall or `make build`
//! executes as root, with the shepherd's full privilege, on every deploy.
//! Nothing here refuses that deploy: this crate's job is to run the build the
//! Flockfile describes, and an app with no `user` is a legitimate
//! configuration that shep itself accepts.
//!
//! That is a deliberate decision by this project's owner rather than an
//! oversight, and it is stated here in full so an operator can act on it:
//! **setting `user` on the app is what turns this module's bound on.**
//! Without it the deploy still works and the failure modes above still
//! hold, a failing build still never reaching the swap, but "a compromised
//! build gets the app's privileges and nothing more" is not one of the
//! guarantees in force. [`run`] warns when it is about to run a build as
//! root with no `user` set; it never refuses one.
//!
//! Three behaviours worth knowing before reading [`run`]'s body:
//!
//! - **An absent build command is a no-op, not an error.** `ReactMap` run
//! as `bun .` compiles its client with vite's own API at startup and
//! declares no build at all; the readiness probe already covers that
//! case, so this module does not need to know a compile happened.
//! - **A failing build is an error that stops everything.** `current`
//! never moves and the running app is untouched, because it lives in a
//! directory the build never touches. This is the part that replaces a
//! hardcoded sleep between a build and a restart.
//! - **`build.artifacts` exists for a build that writes outside the
//! release.** Warm Rust builds do NOT need it: each sheep gets a
//! dog-owned cache symlinked in as `target` (see
//! [`crate::paths::Tree::cache_target`]), so compilation stays warm
//! across releases AND a hardcoded `./target/release/koji` still
//! resolves, with nothing copied back. Setting `CARGO_TARGET_DIR`
//! instead was measured on 2026-08-26 and rejected: with it set
//! `./target` is never created, so Koji's own `make build`, which ends
//! in `cp ./target/release/koji koji`, exits 1. `artifacts` remains for
//! the builds that genuinely do put their output somewhere the release
//! cannot see, including one an operator points elsewhere themselves.
//!
//! ## Where things live
//!
//! - `artifacts`: copying a declared artifact back into the release.
//! - `contain`: the two roots an artifact may land under, and the check by name.
//! - `env`: the cleared build environment.
//! - `privilege`: resolving `user` to a uid and gid, and the root warning.
//! - `runner`: a prepared command run in its own process group, bounded and killed whole.
//! - `walk`: the handle-based walk both ends of a copy go through.
pub
use BTreeMap;
use fmt;
use ;
use Duration;
use Deserialize;
use Command;
use crateError;
use crateprintable;
use copy_artifact;
use artifact_roots;
use ;
/// What to run to turn a freshly checked-out release into something its
/// declared script can execute, and what to salvage from wherever that run
/// actually left its output.
///
/// This is the `[dog.deploy.build]` block of a release's own Flockfile, parsed by
/// [`crate::flockfile::Merged::build_spec`]:
///
/// ```toml
/// [dog.deploy.build]
/// command = "bun install && bun run build"
/// env = { CARGO_TARGET_DIR = "/srv/cache/koji" }
/// artifacts = ["target/release/koji"]
/// ```
///
/// Every field is optional and an absent `[dog.deploy.build]` block is the default
/// value of this struct, which [`run`] treats as a no-op. Unknown keys are
/// refused rather than ignored, matching `shep_core`'s own `AppConfig`: a
/// typo in a build block would otherwise mean a build that silently never
/// runs.
/// Refuses any artifact path that could name something outside the release.
///
/// This runs at parse time, before a build is spawned, because by the time
/// [`copy_artifact`] runs the privilege drop is already behind us: `uid` and
/// `gid` are set on the build's `Command`, so they bound the CHILD, and the
/// copy-back loop runs in this process afterwards at the dog's own uid. Under
/// the arrangement shep's docs recommend, that is root.
///
/// The escape is not hypothetical and the naive case hides it. With no
/// `CARGO_TARGET_DIR`, source and destination are the same expression, so any
/// `..` collapses to `from == to` and [`copy_artifact`]'s self-copy guard
/// returns early. Set `CARGO_TARGET_DIR` and the same string resolves against
/// a different base, so the two differ and the copy proceeds. Measured
/// 2026-08-28: `artifacts = ["target/../../../deploy.toml"]` with
/// `CARGO_TARGET_DIR` set writes through to the tree's own `deploy.toml`,
/// whose `remote` every later fetch reads. A commit on the tracked branch
/// could therefore repoint the deploy at a repository of its own choosing.
///
/// Refused rather than sanitised, matching
/// [`crate::flockfile`]'s treatment of a committed `user`: a path that cannot
/// mean what it says is an operator error worth naming, and silently
/// rewriting one would leave a Flockfile whose text and behaviour disagree.
///
/// # Errors
/// A deserialization error naming the offending path, if any entry is
/// absolute or contains a `..` component.
/// `Debug` does not print `env`'s values (IR-41).
///
/// `env` is exactly the kind of thing that carries secrets - a registry
/// token for a private package feed is an entirely plausible thing to find
/// in a real `build.env` - so this prints how many variables there are and
/// nothing about what they hold. Mirrors `shep_core`'s own `AppConfig`,
/// which redacts its `env` field the same way for the same reason, rather
/// than inventing a second format for the same problem.
/// Runs `spec.command` inside `release`, as `as_user` if given, then copies
/// every declared artifact back into the release.
///
/// An absent `command` is a no-op: `spec.artifacts` is never even
/// consulted, so declaring artifacts alongside no command copies nothing
/// rather than failing to find files a build that never ran could not have
/// produced. See the module doc for why an absent command is the right
/// reading rather than a misconfiguration.
///
/// The command runs through `sh -c`, with `release` as its working
/// directory and an environment built from scratch: [`env::BASE_ENV`], then
/// whatever the operator's `passthrough` names, then `spec.env`, and
/// nothing this process itself inherited beyond those. Its stdout and
/// stderr are inherited rather than captured, so
/// an operator watching a deploy sees the build's real output as it
/// happens instead of a blob replayed after the fact.
///
/// ## The one privilege boundary in this whole crate
///
/// When `as_user` is `Some`, the child drops to that user's uid **and**
/// primary gid - resolved via [`uid_for`]/[`gid_for`] - before it runs
/// anything at all. Uid alone is not enough: the design spec recommends
/// running the shepherd as root specifically so it can drop privileges, and
/// a child that only drops uid keeps whatever gid the shepherd itself was
/// running as - root's group, if the shepherd is root - for the entire
/// build. Dropping the gid too closes that gap, and doing both together
/// also clears supplementary groups for free: `std`'s own process-spawn
/// implementation runs `setgroups(0, ...)` whenever a uid and a gid are
/// both set and no explicit group list is given, which is exactly this
/// call shape (verified against the standard library's own source for the
/// unix `Command` spawn path, since this crate calls no `setgroups` or raw
/// libc itself).
///
/// The build executes code from somebody else's repository, so none of the
/// shepherd's own privilege - uid, primary gid, or supplementary groups -
/// may survive into it: a compromised build then gets the target sheep's
/// uid and gid and nothing more, which is the one control in this whole
/// design that actually bounds damage rather than merely detecting it.
///
/// `child.gid(...)` is called before `child.uid(...)` below, matching the
/// general Unix rule that a process must set its group *before* dropping
/// the uid that lets it change groups at all - reversing the two would
/// leave the gid drop silently ineffective once implemented with raw
/// syscalls. For this specific pair of `tokio::process::Command` builder
/// calls that ordering is not actually load-bearing: verified against the
/// standard library's own unix spawn path, `Command::spawn` performs
/// `setgid` before `setuid` internally whenever either is set, regardless
/// of which order the builder methods were called in. The source-level
/// order below is kept anyway because it reads as the intent it has, and
/// because a future change to how this crate drops privilege - raw
/// `libc::setuid`/`setgid`, or a different process API - would need to
/// preserve the real ordering rule this comment states, not just this
/// call's incidental one.
///
/// A different ordering effect *is* real here, and easy to mistake for the
/// syscall one above: `gid_for(...).await` runs before `uid_for(...).await`
/// textually, so for a user that resolves to neither, `gid_for` is the one
/// that fails and its message is the one `run` returns - not because the
/// privilege drop itself works any differently, but because whichever `id`
/// lookup is awaited first is also the one whose error surfaces first. This
/// is why the reject-side test below pins the specific "gid" wording rather
/// than only `Error::Config(_)`, and why `uid_for`/`gid_for` also each have
/// their own direct test - a `run`-level test alone can only ever observe
/// whichever of the two lookups happens to run first.
///
/// ## A failing build stops everything
///
/// A non-zero exit becomes [`Error::Build`]. This is the guard that keeps
/// a broken build from ever reaching the swap: the caller never moves
/// `current`, and the release being built lives in a directory the
/// running app does not share, so nothing already serving traffic is
/// touched. This is the part that replaces a hardcoded sleep between a
/// build and a restart in the deploy scripts this dog exists to retire.
///
/// # Errors
/// [`Error::Config`] if `as_user` names a user `id -u`/`id -g` cannot
/// resolve, if a declared artifact resolves outside the release and the build
/// cache, or if one the build was meant to produce is not there - see
/// [`copy_artifact`] for all three. [`Error::Io`] naming `release` if the shell
/// (or `id`, for `as_user`) cannot even be launched, and naming the artifact's
/// source, its destination, or that destination's parent if a declared
/// artifact cannot be copied - see [`copy_artifact`], which names the source
/// for the copy itself even when it was the destination that failed.
/// [`Error::Build`] if the command launches and
/// exits non-zero, or is killed by a signal, naming the exit status when there
/// is one. [`Error::BuildTimedOut`] if it runs past `budget`, which is
/// `build_timeout` from the dog's `[deploy]` section.
pub async