shepherd-cli 6.6.1

The canonical shepherd command-line interface over the per-project registry, run artifacts, and sprint pipeline.
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
//! Native extraction and race-safe containment of write-tool targets.

use std::path::{Component, Path};

use serde_json::Value;

use crate::DispatchServiceError;

const WRITE_TOOLS: &[&str] = &["Write", "Edit", "apply_patch"];

/// One write target a hook call names, and whether shepherd governs it.
///
/// The two are separate questions and used to be conflated. A path outside the
/// bound workspace is not malformed -- `~/.claude/.../memory/note.md` is a
/// perfectly well-formed request to write somewhere this repository does not
/// govern -- but it was raised as `InvalidRequest`, which aborts identity
/// resolution for the whole tool call. A session with no dispatch at all then
/// got a hard `PreToolUse` denial reading `invalid dispatch request: absolute
/// write path escapes the bound workspace` for writing to its own home
/// directory.
///
/// It is reported as evidence instead: out of every declared scope by
/// construction, so a dispatched role still cannot write there (the write
/// boundary sees `path_in_write_scope = false` and halts with SCOPE OVERFLOW,
/// which is the accurate halt code), while a session that never opened a
/// sprint resolves normally and is judged by the same rules as any other write.
///
/// A RELATIVE path that climbs out with `..` stays an error. Absolute-and-
/// elsewhere is an honest request; `../../etc/passwd` from inside the
/// repository is an attempt to be read as something it is not.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct WriteTarget {
    /// Repository-relative when inside the workspace, else the original
    /// absolute spelling, so the evidence names what was actually requested.
    pub(crate) path: String,
    /// Whether [`Self::path`] can be judged against a declared dispatch scope.
    pub(crate) inside_workspace: bool,
}

pub(crate) fn derive_write_paths(
    workspace_root: &Path,
    tool_name: Option<&str>,
    tool_input: Option<&Value>,
    exact_root: bool,
) -> Result<Vec<WriteTarget>, DispatchServiceError> {
    let Some(tool_name) = tool_name else {
        if tool_input.is_some() {
            return Err(invalid("tool_input requires tool_name"));
        }
        return Ok(Vec::new());
    };
    if tool_name == "Bash" {
        if exact_root {
            return Ok(Vec::new());
        }
        return Err(invalid(
            "opaque Bash effects cannot receive native write-path authority without shell-text inference",
        ));
    }
    if !WRITE_TOOLS.contains(&tool_name) {
        if tool_input.and_then(Value::as_object).is_some_and(|input| {
            ["file_path", "path", "command"]
                .iter()
                .any(|key| input.contains_key(*key))
        }) {
            return Err(invalid(format!(
                "cannot classify write targets for unknown tool `{tool_name}`"
            )));
        }
        return Ok(Vec::new());
    }
    let input = tool_input.ok_or_else(|| invalid("write tool input is required"))?;
    let freeform_patch = if tool_name == "apply_patch" {
        input.as_str()
    } else {
        None
    };
    let input = match input.as_object() {
        Some(input) => {
            if tool_name == "apply_patch" {
                const APPLY_PATCH_FIELDS: &[&str] =
                    &["file_path", "path", "patch", "input", "operation"];
                if let Some(field) = input
                    .keys()
                    .find(|field| !APPLY_PATCH_FIELDS.contains(&field.as_str()))
                {
                    return Err(invalid(format!(
                        "apply_patch input contains unknown field `{field}`"
                    )));
                }
                if input.contains_key("patch") && input.contains_key("input") {
                    return Err(invalid(
                        "apply_patch input must not contain both `patch` and `input`",
                    ));
                }
            }
            Some(input)
        }
        None if freeform_patch.is_some() => None,
        None => return Err(invalid("write tool input must be an object")),
    };
    let mut raw = Vec::new();
    if let Some(input) = input {
        for key in ["file_path", "path"] {
            if let Some(value) = input.get(key) {
                raw.push(
                    value
                        .as_str()
                        .filter(|value| !value.is_empty())
                        .ok_or_else(|| invalid(format!("tool_input.{key} must be a string")))?,
                );
            }
        }
    }
    let object_patch = input
        .and_then(|input| input.get("patch").or_else(|| input.get("input")))
        .map(|value| {
            value
                .as_str()
                .ok_or_else(|| invalid("apply_patch input must be a string"))
        })
        .transpose()?;
    if let Some(patch) = freeform_patch.or(object_patch) {
        raw.extend(extract_patch_paths(patch)?);
    }
    raw.sort_unstable();
    raw.dedup();
    if raw.is_empty() {
        return Err(invalid(format!(
            "cannot derive native write path from `{tool_name}` input"
        )));
    }

    let mut paths = Vec::with_capacity(raw.len());
    for candidate in raw {
        match normalize_relative(workspace_root, candidate)? {
            Some(relative) => {
                verify_nofollow(workspace_root, &relative)?;
                paths.push(WriteTarget {
                    path: relative,
                    inside_workspace: true,
                });
            }
            // `verify_nofollow` is rooted at the workspace, so there is nothing
            // for it to walk here. Nothing is opened, which is the point: this
            // path is reported, not reached.
            None => paths.push(WriteTarget {
                path: candidate.to_owned(),
                inside_workspace: false,
            }),
        }
    }
    paths.sort_by(|left, right| left.path.cmp(&right.path));
    paths.dedup();
    Ok(paths)
}

fn extract_patch_paths(patch: &str) -> Result<Vec<&str>, DispatchServiceError> {
    if patch.len() > 1_048_576 || patch.contains('\0') {
        return Err(invalid("apply_patch input is unsafe or too large"));
    }
    let mut paths = Vec::new();
    for line in patch.lines() {
        for prefix in [
            "*** Add File: ",
            "*** Update File: ",
            "*** Delete File: ",
            "*** Move to: ",
        ] {
            if let Some(path) = line.strip_prefix(prefix) {
                if path.is_empty() || path.trim() != path {
                    return Err(invalid("apply_patch contains an invalid path header"));
                }
                paths.push(path);
            }
        }
    }
    if paths.is_empty() {
        return Err(invalid("apply_patch contains no canonical file headers"));
    }
    Ok(paths)
}

/// The repository-relative form of one write target, or `None` when the target
/// is a well-formed absolute path outside the workspace. See [`WriteTarget`].
fn normalize_relative(
    workspace_root: &Path,
    candidate: &str,
) -> Result<Option<String>, DispatchServiceError> {
    // A backslash is a LITERAL filename character on unix, so smuggling one
    // into a write path is a real attempt to confuse a downstream consumer and
    // is refused. On Windows it is THE separator, so refusing it rejected every
    // absolute path the platform produces. Normalizing first keeps one rule.
    let normalized;
    let candidate = if cfg!(windows) {
        normalized = candidate.replace('\\', "/");
        normalized.as_str()
    } else {
        candidate
    };
    if candidate.len() > 4_096
        || (!cfg!(windows) && candidate.contains('\\'))
        || candidate.contains('\0')
        || candidate.chars().any(char::is_control)
    {
        return Err(invalid("write path is unsafe"));
    }
    let candidate = Path::new(candidate);
    let resolved;
    let relative = if candidate.is_absolute() {
        // Compare by identity, not by spelling. One side of this comparison
        // arrives canonicalized by `ExecutionContext` and the other arrives as
        // the caller typed it, and on Windows those are routinely different
        // spellings of the same directory -- verbatim vs plain, long name vs
        // 8.3 short name -- so a containment check on the raw strings refused
        // paths that were plainly inside the repository.
        resolved = crate::interface::canonical_identity(candidate);
        let root = crate::interface::canonical_identity(workspace_root);
        match resolved.strip_prefix(&root) {
            Ok(relative) => relative,
            // Outside the workspace: reported, not refused.
            Err(_) => return Ok(None),
        }
    } else {
        candidate
    };
    let mut parts = Vec::new();
    for component in relative.components() {
        match component {
            Component::Normal(part) => {
                let value = part
                    .to_str()
                    .ok_or_else(|| invalid("write path must be UTF-8"))?;
                if value.is_empty() || value == "." || value == ".." {
                    return Err(invalid("write path has an unsafe component"));
                }
                parts.push(value);
            }
            _ => {
                return Err(invalid(
                    "write path must be normalized and repository-relative",
                ));
            }
        }
    }
    if parts.is_empty() {
        return Err(invalid("write path cannot name the repository root"));
    }
    Ok(Some(parts.join("/")))
}

#[cfg(unix)]
fn verify_nofollow(workspace_root: &Path, relative: &str) -> Result<(), DispatchServiceError> {
    use rustix::fs::{FileType, Mode, OFlags, open, openat};

    let mut directory = open(
        workspace_root,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
        Mode::empty(),
    )
    .map_err(|error| {
        invalid(format!(
            "cannot open bound workspace without following links: {error}"
        ))
    })?;
    let parts: Vec<&str> = relative.split('/').collect();
    for (index, part) in parts.iter().enumerate() {
        let final_component = index + 1 == parts.len();
        let flags = if final_component {
            OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW
        } else {
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW
        };
        match openat(&directory, *part, flags, Mode::empty()) {
            Ok(next) if final_component => {
                let stat = rustix::fs::fstat(&next)
                    .map_err(|error| invalid(format!("cannot inspect write target: {error}")))?;
                if !FileType::from_raw_mode(stat.st_mode).is_file() {
                    return Err(invalid("existing write target is not a regular file"));
                }
            }
            Ok(next) => directory = next,
            Err(error) if final_component && error == rustix::io::Errno::NOENT => return Ok(()),
            Err(error) => {
                return Err(invalid(format!(
                    "write target is not safely contained without following links: {error}"
                )));
            }
        }
    }
    Ok(())
}

/// The non-unix twin. Same three verdicts as the unix walk: an absent final
/// component is allowed (the write is about to create it), an existing final
/// component must be a regular file, and a link anywhere in the chain is
/// refused.
#[cfg(not(unix))]
fn verify_nofollow(workspace_root: &Path, relative: &str) -> Result<(), DispatchServiceError> {
    if crate::safe_fs::is_link(workspace_root)
        .map_err(|error| invalid(format!("cannot inspect bound workspace: {error}")))?
    {
        return Err(invalid(
            "cannot open bound workspace without following links: it is a symlink",
        ));
    }
    let mut walked = workspace_root.to_path_buf();
    let parts: Vec<&str> = relative.split('/').collect();
    for (index, part) in parts.iter().enumerate() {
        walked.push(part);
        let final_component = index + 1 == parts.len();
        let metadata = match std::fs::symlink_metadata(&walked) {
            Ok(metadata) => metadata,
            Err(error) if final_component && error.kind() == std::io::ErrorKind::NotFound => {
                return Ok(());
            }
            Err(error) => {
                return Err(invalid(format!(
                    "write target is not safely contained without following links at {}: {error}",
                    walked.display()
                )));
            }
        };
        if metadata.file_type().is_symlink() {
            return Err(invalid(
                "write target is not safely contained without following links: it traverses a symlink",
            ));
        }
        if final_component {
            if !metadata.is_file() {
                return Err(invalid("existing write target is not a regular file"));
            }
        } else if !metadata.is_dir() {
            return Err(invalid(
                "write target is not safely contained without following links: an intermediate component is not a directory",
            ));
        }
    }
    Ok(())
}

fn invalid(reason: impl Into<String>) -> DispatchServiceError {
    DispatchServiceError::InvalidRequest(reason.into())
}

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

    /// The repository-relative spellings, for assertions that only care about
    /// which paths a call named.
    fn inside(targets: Vec<WriteTarget>) -> Vec<String> {
        targets
            .into_iter()
            .map(|target| {
                assert!(
                    target.inside_workspace,
                    "unexpected out-of-workspace target"
                );
                target.path
            })
            .collect()
    }

    #[test]
    fn apply_patch_preserves_object_and_freeform_payloads_but_rejects_unknown_fields() {
        let root = std::env::temp_dir();
        let path = format!("shepherd-apply-patch-{}.md", std::process::id());
        let patch = format!("*** Begin Patch\n*** Update File: {path}\n*** End Patch");

        assert_eq!(
            derive_write_paths(
                &root,
                Some("apply_patch"),
                Some(&serde_json::json!({"patch": patch})),
                false,
            )
            .map(inside)
            .expect("object payload"),
            vec![path.clone()]
        );
        assert_eq!(
            derive_write_paths(
                &root,
                Some("apply_patch"),
                Some(&serde_json::Value::String(patch.clone())),
                false,
            )
            .map(inside)
            .expect("freeform payload"),
            vec![path]
        );
        assert!(
            derive_write_paths(
                &root,
                Some("apply_patch"),
                Some(&serde_json::json!({"patch": patch, "untrusted": true})),
                false,
            )
            .is_err(),
            "unknown apply_patch fields must fail closed"
        );
    }

    #[test]
    fn opaque_bash_and_unclassifiable_write_tools_fail_closed() {
        let root = std::env::temp_dir().join("shepherd-dispatch-scope-red");
        assert!(
            derive_write_paths(
                &root,
                Some("Bash"),
                Some(&serde_json::json!({
                    "command": "printf unsafe"
                })),
                false,
            )
            .is_err()
        );
        assert!(
            derive_write_paths(
                &root,
                Some("UnknownWrite"),
                Some(&serde_json::json!({
                    "path": "docs/report.md"
                })),
                false,
            )
            .is_err()
        );
    }

    #[test]
    fn exact_root_bash_has_no_derived_paths_and_unknown_tools_still_fail_closed() {
        let root = std::env::temp_dir().join("shepherd-dispatch-scope-root");
        assert_eq!(
            derive_write_paths(
                &root,
                Some("Bash"),
                Some(&serde_json::json!({
                    "command": "printf text > docs/report.md && git status --short --branch"
                })),
                true,
            )
            .map(inside)
            .expect("exact root Bash is authorized by native identity, not inferred shell paths"),
            Vec::<String>::new(),
        );
        assert!(
            derive_write_paths(
                &root,
                Some("UnknownWrite"),
                Some(&serde_json::json!({"command": "true"})),
                true,
            )
            .is_err(),
            "exact root authority must not classify unknown tools"
        );
    }

    /// A well-formed absolute path outside the workspace is EVIDENCE, not an
    /// error.
    ///
    /// It used to raise `InvalidRequest`, which aborts identity resolution for
    /// the whole tool call, so a session with no dispatch at all was denied
    /// `PreToolUse` for writing to its own home directory. The security
    /// property is unchanged and better expressed: the target is reported with
    /// `inside_workspace = false`, which is outside every declared scope by
    /// construction, so the write boundary halts a dispatched role with SCOPE
    /// OVERFLOW instead of a message about a malformed request.
    #[test]
    fn an_absolute_path_outside_the_workspace_is_reported_not_refused() {
        let root = std::env::temp_dir().join("shepherd-dispatch-scope-outside");
        // Absolute on the platform under test. A unix-shaped path is NOT
        // absolute on Windows -- `Path::is_absolute` wants a drive prefix --
        // so a hardcoded `/Users/...` took the relative branch there and the
        // assertion below failed for a reason that had nothing to do with the
        // property.
        let outside = if cfg!(windows) {
            r"C:\Users\nobody\.claude\memory\note.md"
        } else {
            "/Users/nobody/.claude/memory/note.md"
        };
        let targets = derive_write_paths(
            &root,
            Some("Write"),
            Some(&serde_json::json!({"file_path": outside})),
            false,
        )
        .expect("an out-of-workspace write resolves rather than aborting the call");

        assert_eq!(
            targets,
            vec![WriteTarget {
                path: outside.to_owned(),
                inside_workspace: false,
            }],
            "the evidence names the path that was actually requested"
        );
    }

    /// A RELATIVE path climbing out with `..` stays an error.
    ///
    /// Absolute-and-elsewhere is an honest request. `../../etc/passwd` from
    /// inside the repository is an attempt to be read as something it is not,
    /// and the line between them is the whole reason the relaxation above is
    /// safe.
    #[test]
    fn a_relative_path_that_climbs_out_of_the_workspace_still_fails_closed() {
        let root = std::env::temp_dir().join("shepherd-dispatch-scope-climb");
        for candidate in ["../escape.md", "docs/../../escape.md", "./../escape.md"] {
            assert!(
                derive_write_paths(
                    &root,
                    Some("Write"),
                    Some(&serde_json::json!({"file_path": candidate})),
                    false,
                )
                .is_err(),
                "{candidate} must not resolve"
            );
        }
    }
}