跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

scan.go

800 行 · 23.1 KB历史下载
1// Package gitguard finds what git on this machine runs, or reads, from the
2// folders a VM can write: hooks, and commands its config names. The VM can
3// write the project and the writable volumes; git runs hooks and commands
4// from paths anywhere, in the repository's own share, in another share
5// (core.hooksPath into a volume), or from git's own config kept in one. Each
6// path is followed through every symlink on the way, and checked against
7// every share.
8package gitguard
9
10import (
11 "context"
12 "errors"
13 "fmt"
14 "io/fs"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "regexp"
19 "slices"
20 "strings"
21 "time"
22 "unicode"
23 "unicode/utf8"
24
25 "github.com/sylvinus/agent-vm/internal/gitx"
26 "github.com/sylvinus/agent-vm/internal/mounts"
27 "github.com/sylvinus/agent-vm/internal/paths"
28)
29
30// Spelling is dir as git spells it: the physical path, C:/... on Windows.
31func Spelling(dir string) (string, bool) {
32 p, err := filepath.EvalSymlinks(dir)
33 if err != nil {
34 return "", false
35 }
36 if !filepath.IsAbs(p) {
37 if p, err = filepath.Abs(p); err != nil {
38 return "", false
39 }
40 }
41 return filepath.ToSlash(p), true
42}
43
44// gitAbs is p made absolute against base (both in git's spelling), "." and
45// ".." resolved in the text.
46func gitAbs(p, base string) string {
47 switch {
48 case strings.HasPrefix(p, "/"):
49 return paths.Join("/", p)
50 case len(p) >= 3 && p[1] == ':' && p[2] == '/' && isLetter(p[0]):
51 return paths.Join(p[:2], p[3:])
52 }
53 return paths.Join(base, p)
54}
55
56func isLetter(c byte) bool { return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' }
57
58// isAbs: /... or C:/...
59func isAbs(p string) bool {
60 return strings.HasPrefix(p, "/") || len(p) >= 3 && p[1] == ':' && p[2] == '/' && isLetter(p[0])
61}
62
63// Shares are the folders the VM can write, in git's spelling, each once:
64// the project first, then its writable volumes.
65func Shares(project string, rwVolumes []string) []string {
66 var out []string
67 seen := map[string]bool{}
68 for _, d := range append([]string{project}, rwVolumes...) {
69 if d == "" {
70 continue
71 }
72 if s, ok := Spelling(d); ok && !seen[s] {
73 seen[s] = true
74 out = append(out, s)
75 }
76 }
77 return out
78}
79
80// scan is one run over the shares.
81type scan struct {
82 ctx context.Context
83 shares []string
84 proj string
85 home string
86 hooks []string // see Result
87 risks []risk
88 seen map[string]bool
89}
90
91// emit adds a hooks line, once.
92func (s *scan) emit(line string) {
93 if !s.seen[line] {
94 s.seen[line] = true
95 s.hooks = append(s.hooks, line)
96 }
97}
98
99// inShare is the deepest share holding p, and p relative to it ("." for the
100// share itself).
101func (s *scan) inShare(p string) (share, rel string, ok bool) {
102 for _, d := range s.shares {
103 d = strings.TrimSuffix(d, "/")
104 if d == "" {
105 continue
106 }
107 if r, in := paths.In(p, d); in && len(d) > len(share) {
108 share, rel, ok = d, r, true
109 }
110 }
111 return
112}
113
114// hops is every path the file system goes through to reach p (absolute, in
115// git's spelling): p; each symlink on the way, wherever it is in the path,
116// as the link itself (the VM, able to write it, retargets it); and where it
117// all leads, whether that exists or not (the VM can create it). Followed
118// one component at a time, up to 40 links. A VM able to write any of them
119// chooses what is found there.
120func hops(p string) []string {
121 out := []string{p}
122 seen := map[string]bool{p: true}
123 add := func(q string) {
124 if !seen[q] {
125 seen[q] = true
126 out = append(out, q)
127 }
128 }
129 root, rest := "/", strings.TrimPrefix(p, "/")
130 if len(p) >= 3 && p[1] == ':' && p[2] == '/' {
131 root, rest = p[:3], p[3:]
132 }
133 cur := strings.TrimSuffix(root, "/")
134 links := 0
135 for rest != "" {
136 var comp string
137 comp, rest, _ = strings.Cut(rest, "/")
138 switch comp {
139 case "", ".":
140 continue
141 case "..":
142 cur = cur[:max(strings.LastIndexByte(cur, '/'), 0)]
143 continue
144 }
145 next := cur + "/" + comp
146 fi, err := os.Lstat(next)
147 if err != nil {
148 // Not there: what follows is where the VM could create it.
149 cur = next
150 if rest != "" {
151 cur += "/" + strings.TrimSuffix(rest, "/")
152 }
153 rest = ""
154 break
155 }
156 if fi.Mode()&fs.ModeSymlink == 0 {
157 cur = next
158 continue
159 }
160 add(next)
161 if links++; links > 40 {
162 return out
163 }
164 t, err := os.Readlink(next)
165 if err != nil {
166 return out
167 }
168 t = filepath.ToSlash(t)
169 if isAbs(t) {
170 r := "/"
171 if t[0] != '/' {
172 r = t[:3]
173 }
174 cur, t = strings.TrimSuffix(r, "/"), strings.TrimPrefix(t, r)
175 }
176 if rest != "" {
177 t += "/" + rest
178 }
179 rest = t
180 }
181 if cur == "" {
182 cur = "/"
183 }
184 add(cur)
185 return out
186}
187
188// gitTimeout bounds each call to git: a hung one (a network file system, a
189// config program waiting on a prompt) must not stall the start.
190var gitTimeout = 15 * time.Second
191
192// gitError is a failed call to git: its exit status (-1 when it did not run
193// to the end) and the first line it said on stderr.
194type gitError struct {
195 code int
196 msg string
197}
198
199func (e *gitError) Error() string {
200 if e.msg == "" {
201 return fmt.Sprintf("git exited with status %d", e.code)
202 }
203 return e.msg
204}
205
206// notRepo: git found no repository there, which is no failure to check.
207func notRepo(err error) bool {
208 return err != nil && strings.Contains(err.Error(), "not a git repository")
209}
210
211// unset: `git config --get` found no such key.
212func unset(err error) bool {
213 var ge *gitError
214 return errors.As(err, &ge) && ge.code == 1 && ge.msg == ""
215}
216
217// git runs git for the repository at of kind kind: W a work tree, B a bare
218// repository (named explicitly, as safe.bareRepository=explicit allows), G
219// none, for git's own global and system config. The output is git's as is.
220func (s *scan) git(kind, at string, args ...string) ([]byte, error) {
221 switch kind {
222 case "W":
223 args = append([]string{"-C", at}, args...)
224 case "B":
225 args = append([]string{"--git-dir=" + at}, args...)
226 default:
227 args = append([]string{"-C", "/"}, args...)
228 }
229 ctx, cancel := context.WithTimeout(s.ctx, gitTimeout)
230 defer cancel()
231 cmd := gitx.Untrusted(ctx, args...)
232 // Messages in English: notRepo reads them.
233 cmd.Env = append(os.Environ(), "LC_ALL=C", "LANGUAGE=C")
234 cmd.WaitDelay = 2 * time.Second
235 out, err := cmd.Output()
236 if err == nil {
237 return out, nil
238 }
239 if ctx.Err() != nil {
240 return nil, &gitError{-1, "git did not answer in time"}
241 }
242 var ee *exec.ExitError
243 if errors.As(err, &ee) {
244 msg, _, _ := strings.Cut(strings.TrimSpace(string(ee.Stderr)), "\n")
245 return out, &gitError{ee.ExitCode(), msg}
246 }
247 return nil, &gitError{-1, err.Error()}
248}
249
250// line is the output of a command printing one value, as git ends it.
251func line(out []byte) string { return strings.TrimSuffix(string(out), "\n") }
252
253// unchecked adds the risk of something the scan could not look at: nothing
254// is known of it, which is not the same as nothing being there.
255func (s *scan) unchecked(what, where string, err error) {
256 s.risk(risk{text: "could not check " + what + " of " + s.name(where) + ": " + err.Error()})
257}
258
259// name is p as shown to the user.
260func (s *scan) name(p string) string {
261 if p = s.shown(p); p == "." {
262 return "the project"
263 }
264 return p
265}
266
267// repo is a repository found in a share.
268type repo struct{ kind, at string }
269
270const (
271 // maxRepos is how many repositories are checked in a share.
272 maxRepos = 50
273 // maxRepoDepth is how many folders down from a share a repository's root
274 // is looked for.
275 maxRepoDepth = 6
276)
277
278// maxFolders is how many folders are read looking for them, per share.
279var maxFolders = 20000
280
281// repos are those git on this machine finds in the share dir: the one
282// holding dir, then work trees and bare repositories up to maxRepoDepth
283// levels below it (node_modules skipped), maxRepos at most; an X entry when
284// there are more. Reading more than maxFolders folders stops the search, said
285// as a risk.
286func (s *scan) repos(dir string) []repo {
287 var out []repo
288 if _, err := s.git("W", dir, "rev-parse", "--git-dir"); err == nil {
289 out = append(out, repo{"W", dir})
290 } else if !notRepo(err) {
291 s.unchecked("the repository", dir, err)
292 }
293 n, folders := 0, 0
294 found := func(g string) bool {
295 if n++; n > maxRepos {
296 out = append(out, repo{"X", dir})
297 return false
298 }
299 if _, err := os.Lstat(g + "/.git"); err == nil {
300 out = append(out, repo{"W", g})
301 } else {
302 out = append(out, repo{"B", g})
303 }
304 return true
305 }
306 // As `find dir/ -mindepth 2 -maxdepth N ( -name node_modules -prune ) -o
307 // ( -name .git -print -prune ) -o ( -name objects -type d -print -prune )`,
308 // and no .git entered.
309 var walk func(d string, depth int) bool
310 walk = func(d string, depth int) bool {
311 if folders++; folders > maxFolders {
312 s.risk(risk{text: fmt.Sprintf("repositories in %s: stopped looking after %d folders", s.name(dir), maxFolders)})
313 return false
314 }
315 ents, err := os.ReadDir(d)
316 if err != nil {
317 if !errors.Is(err, fs.ErrNotExist) {
318 s.unchecked("the folder", d, err)
319 }
320 return true
321 }
322 for _, e := range ents {
323 p := d + "/" + e.Name()
324 if depth+1 >= 2 {
325 switch {
326 case e.Name() == "node_modules":
327 continue
328 case e.Name() == ".git":
329 if !found(d) {
330 return false
331 }
332 continue
333 case e.Name() == "objects" && e.IsDir():
334 if isFile(d+"/HEAD") && isDir(d+"/refs") && !found(d) {
335 return false
336 }
337 continue
338 }
339 }
340 if e.Name() != ".git" && depth+1 <= maxRepoDepth && e.IsDir() {
341 if !walk(p, depth+1) {
342 return false
343 }
344 }
345 }
346 return true
347 }
348 walk(strings.TrimSuffix(dir, "/"), 0)
349 return out
350}
351
352func isFile(p string) bool { fi, err := os.Stat(p); return err == nil && fi.Mode().IsRegular() }
353func isDir(p string) bool { fi, err := os.Stat(p); return err == nil && fi.IsDir() }
354
355// hooksDir is the hooks folder of the repository at of kind kind, absolute,
356// in git's spelling, as git names it (symlinks not resolved), and the top
357// of the work tree for W. For G, the absolute core.hooksPath git's own
358// config sets for every repository.
359func (s *scan) hooksDir(kind, at string) (top, hooks string, ok bool) {
360 base := "/"
361 switch kind {
362 case "G":
363 out, err := s.git("G", "/", "config", "--get", "core.hooksPath")
364 if err != nil {
365 if !unset(err) {
366 s.risk(risk{text: "could not check git's own config: " + err.Error()})
367 }
368 return "", "", false
369 }
370 hooks = line(out)
371 if strings.HasPrefix(hooks, "~/") {
372 hooks = s.home + hooks[1:]
373 }
374 if !isAbs(hooks) {
375 return "", "", false
376 }
377 case "W":
378 // Two calls: a path may hold a newline, which would split one.
379 out, err := s.git("W", at, "rev-parse", "--show-toplevel")
380 if err == nil {
381 top = line(out)
382 } else if strings.Contains(err.Error(), "work tree") {
383 // Inside a repository's own folder: no top.
384 err = nil
385 }
386 if err == nil {
387 out, err = s.git("W", at, "rev-parse", "--git-path", "hooks")
388 hooks = line(out)
389 }
390 if err != nil {
391 if !notRepo(err) {
392 s.unchecked("the hooks", at, err)
393 }
394 return "", "", false
395 }
396 if base, ok = Spelling(at); !ok {
397 return "", "", false
398 }
399 default:
400 out, err := s.git(kind, at, "rev-parse", "--git-path", "hooks")
401 if err != nil {
402 if !notRepo(err) {
403 s.unchecked("the hooks", at, err)
404 }
405 return "", "", false
406 }
407 hooks = line(out)
408 // A relative core.hooksPath is taken from the repository's folder.
409 if kind == "B" {
410 base = at
411 }
412 }
413 if hooks == "" {
414 return "", "", false
415 }
416 return top, gitAbs(hooks, base), true
417}
418
419// hop is a path the VM can write on the way to something git runs: shown
420// relative to the project when it is there, and relative to its share,
421// where the read-only names apply.
422type hop struct{ shown, rel string }
423
424// hits are the paths on the way to p (see hops) in a share and outside the
425// names always listed, in order. Which of them a hooks name keeps read-only
426// is only known once the user answered (see Result.Risks).
427func (s *scan) hits(p string) []hop {
428 if p == "" {
429 return nil
430 }
431 var out []hop
432 for _, h := range hops(p) {
433 _, rel, ok := s.inShare(h)
434 if !ok || mounts.UnderName(rel, nil) {
435 continue
436 }
437 out = append(out, hop{s.shown(h), rel})
438 }
439 return out
440}
441
442// shown is p relative to the project when it is there, a writable volume
443// inside it included, else p.
444func (s *scan) shown(p string) string {
445 if r, ok := paths.In(p, s.proj); ok {
446 return r
447 }
448 return p
449}
450
451// risk is a risk to accept: text, or prefix and the first of hops no name
452// protects. A risk with prefix and no hops is no risk.
453type risk struct {
454 prefix, text string
455 hops []hop
456}
457
458func (s *scan) risk(r risk) {
459 if r.prefix != "" && len(r.hops) == 0 {
460 return
461 }
462 s.risks = append(s.risks, r)
463}
464
465// unprintable: a control character, or one that prints nothing or reorders
466// text (U+202E, zero-width characters...), but a space.
467func unprintable(r rune) bool { return r != ' ' && !unicode.IsPrint(r) }
468
469// visible is t with what a terminal would act on, or what hides text,
470// replaced by "?".
471func visible(t string) string {
472 return strings.Map(func(r rune) rune {
473 if unprintable(r) {
474 return '?'
475 }
476 return r
477 }, t)
478}
479
480// The settings that hold a command git runs, or a folder whose hooks it
481// copies (section and key names lowercased, as `git config --list` prints
482// them). hook.<name>.command is git 2.54's; imap.tunnel is git imap-send's;
483// the lfs ones are git-lfs's, which git runs through its filters.
484var commandKey = regexp.MustCompile(`^(core\.(fsmonitor|sshcommand|editor|pager|askpass|gitproxy|alternaterefscommand)|sequence\.editor|gpg\.program|gpg\..*\.program|gpg\.ssh\.defaultkeycommand|diff\.external|diff\..*\.(command|textconv)|(difftool|mergetool|browser|man)\..*\.(cmd|path)|guitool\..*\.cmd|merge\..*\.driver|filter\..*\.(clean|smudge|process)|credential\.helper|credential\..*\.helper|pager\..*|alias\..*|interactive\.difffilter|uploadpack\.packobjectshook|web\.browser|instaweb\.httpd|trailer\..*\.(cmd|command)|submodule\..*\.update|remote\..*\.(uploadpack|receivepack)|tar\..*\.command|sendemail\.(.*\.)?(smtpserver|sendmailcmd|tocmd|cccmd|headercmd)|hook\..*\.command|imap\.tunnel|lfs\.customtransfer\..*\.path|lfs\.extension\..*\.(clean|smudge)|init\.templatedir)$`)
485
486// unquote is w with one quote of either kind off each end.
487func unquote(w string) string {
488 if w != "" && (w[0] == '"' || w[0] == '\'') {
489 w = w[1:]
490 }
491 if n := len(w); n > 0 && (w[n-1] == '"' || w[n-1] == '\'') {
492 w = w[:n-1]
493 }
494 return w
495}
496
497var includeKey = regexp.MustCompile(`^includeif\..*\.path$`)
498
499// config reports the risks of the config git reads for the repository at of
500// kind kind, whose work tree is cmdBase: config files in a share (included
501// ones whether they exist yet or not: git skips a missing one, and the VM
502// can create it), and settings whose command a share holds, a path in their
503// value taken from the top of the repository, where git runs most of them.
504func (s *scan) config(kind, at, cmdBase string) {
505 base := "/"
506 switch kind {
507 case "W":
508 var ok bool
509 if base, ok = Spelling(at); !ok {
510 return
511 }
512 case "B":
513 cmdBase = at
514 }
515 // -z: each entry is its origin, a NUL, the key, a newline, the value, a
516 // NUL. Origins come unquoted, whatever their characters.
517 out, err := s.git(kind, at, "config", "--list", "--show-origin", "--includes", "-z")
518 if err != nil {
519 if !notRepo(err) {
520 s.unchecked("the config", at, err)
521 }
522 return
523 }
524 fields := strings.Split(string(out), "\x00")
525 seenFile := map[string]bool{}
526 for i := 0; i+1 < len(fields); i += 2 {
527 origin, kv := fields[i], fields[i+1]
528 f, _ := strings.CutPrefix(origin, "file:")
529 if !strings.HasPrefix(origin, "file:") {
530 f = ""
531 }
532 if f != "" && !seenFile[f] {
533 seenFile[f] = true
534 s.risk(risk{prefix: "config file ", hops: s.hits(gitAbs(filepath.ToSlash(f), base))})
535 }
536 key, val, _ := strings.Cut(kv, "\n")
537 lk := strings.ToLower(key)
538 if lk == "include.path" || includeKey.MatchString(lk) {
539 if f == "" {
540 continue
541 }
542 // Relative to the file holding it, as git takes it.
543 if strings.HasPrefix(val, "~/") {
544 val = s.home + val[1:]
545 }
546 a := gitAbs(filepath.ToSlash(f), base)
547 s.risk(risk{prefix: "config file ", hops: s.hits(gitAbs(val, a[:strings.LastIndexByte(a, '/')]))})
548 continue
549 }
550 if !commandKey.MatchString(lk) || strings.HasPrefix(lk, "alias.") && !strings.HasPrefix(val, "!") {
551 continue
552 }
553 // One risk for the setting, with the paths of every word: the first
554 // no name protects is the one that counts.
555 r := risk{text: key + " = " + val}
556 for i, w := range strings.FieldsFunc(strings.TrimPrefix(val, "!"), func(r rune) bool { return r == ' ' || r == '\t' }) {
557 w = unquote(w)
558 // An assignment or an option's value (--upload-pack=./x, or
559 // ProxyCommand=./x after ssh's -o): the word is what follows the
560 // =, and only a path counts.
561 if _, after, ok := strings.Cut(w, "="); ok {
562 if w = unquote(after); !strings.Contains(w, "/") {
563 continue
564 }
565 }
566 // Not an option or a URL: a path.
567 if w == "" || strings.HasPrefix(w, "-") || strings.Contains(w, "://") {
568 continue
569 }
570 // Without a /, the command is found on PATH; an argument is a
571 // file from where git runs it (bash build.sh) when there is one
572 // there: not every word (git log) is taken for one.
573 if !strings.Contains(w, "/") {
574 if i == 0 || cmdBase == "" {
575 continue
576 }
577 if _, err := os.Lstat(gitAbs(w, cmdBase)); err != nil {
578 continue
579 }
580 }
581 if strings.HasPrefix(w, "~/") {
582 w = s.home + w[1:]
583 }
584 if !isAbs(w) && cmdBase == "" {
585 continue
586 }
587 r.hops = append(r.hops, s.hits(gitAbs(w, cmdBase))...)
588 }
589 if len(r.hops) > 0 {
590 s.risk(r)
591 }
592 }
593}
594
595// Result is what git on this machine runs, or reads, from the shares.
596type Result struct {
597 // Hooks are the hooks folders, or links on the way to them, in a share
598 // and outside the names always listed, each once: where (relative to
599 // the project when it is there, else absolute), a tab, then what names
600 // it (see HooksName): relative to the top of its repository when that
601 // is in a share, else to the share; "." when no name covers it (a share
602 // itself, or a name at or above the root of the share holding it),
603 // empty for a name no share can carry.
604 Hooks []string
605 risks []risk
606}
607
608// Risks are the risks to accept, as text, each once, when the shares get
609// names (the names always listed, and the hooks names accepted): a config
610// file in a share, a setting whose command is in one, a hook linked to a
611// file in one, a share with more repositories than are checked, something git
612// could not be asked about (an error, no answer in time). What a
613// name keeps read-only is no risk; a declined hooks name keeps nothing.
614func (r *Result) Risks(names []string) []string {
615 var out []string
616 seen := map[string]bool{}
617 for _, k := range r.risks {
618 t := k.text
619 if len(k.hops) > 0 {
620 t = ""
621 for _, h := range k.hops {
622 if !mounts.UnderName(h.rel, names) {
623 t = k.text
624 if t == "" {
625 t = k.prefix + h.shown
626 }
627 break
628 }
629 }
630 }
631 if t = visible(t); t != "" && !seen[t] {
632 seen[t] = true
633 out = append(out, t)
634 }
635 }
636 return out
637}
638
639// Names are the names always listed, then those keeping every hooks folder
640// read-only, each once: the names when every one is accepted.
641func (r *Result) Names() []string {
642 var hooks []string
643 for _, h := range r.Hooks {
644 _, inRepo, _ := strings.Cut(h, "\t")
645 if n, ok := HooksName(inRepo); ok {
646 hooks = append(hooks, n)
647 }
648 }
649 return NamesWith(hooks)
650}
651
652// NamesWith is the names always listed, then hooks, each once.
653func NamesWith(hooks []string) []string {
654 out := append([]string(nil), mounts.BaseNames...)
655 for _, n := range hooks {
656 if !slices.Contains(out, n) {
657 out = append(out, n)
658 }
659 }
660 return out
661}
662
663// Lines are the hooks folders and the risks, every hooks name accepted, as
664// 0.2 printed them: "H\t" or "R\t" and the rest.
665func (r *Result) Lines() []string {
666 var out []string
667 for _, h := range r.Hooks {
668 out = append(out, "H\t"+h)
669 }
670 for _, t := range r.Risks(r.Names()) {
671 out = append(out, "R\t"+t)
672 }
673 return out
674}
675
676// Scan is what git on this machine runs, or reads, from the shares (see
677// Shares; the project first). home is the user's home folder.
678func Scan(ctx context.Context, shares []string, home string) *Result {
679 if !gitx.Have() || len(shares) == 0 {
680 return &Result{}
681 }
682 s := &scan{ctx: ctx, shares: shares, proj: shares[0], home: filepath.ToSlash(home), seen: map[string]bool{}}
683 var all []repo
684 for _, sh := range shares {
685 all = append(all, s.repos(sh)...)
686 }
687 all = append(all, repo{"G", "/"})
688 var rs []repo
689 for _, r := range all {
690 if r.kind != "X" {
691 rs = append(rs, r)
692 continue
693 }
694 shown := r.at
695 if share, rel, ok := s.inShare(r.at); ok && share == s.proj {
696 shown = rel
697 if rel == "." {
698 shown = "the project"
699 }
700 }
701 s.risk(risk{text: "more than 50 repositories in " + shown + ": those after the 50th are not checked"})
702 }
703 // The hooks folders first: their names keep what is under them read-only.
704 hookss := make([]string, len(rs))
705 tops := make([]string, len(rs))
706 for i, r := range rs {
707 top, hooks, ok := s.hooksDir(r.kind, r.at)
708 if !ok && r.kind == "W" {
709 if out, err := s.git("W", r.at, "rev-parse", "--show-toplevel"); err == nil {
710 top = line(out)
711 }
712 }
713 hookss[i], tops[i] = hooks, top
714 if hooks == "" {
715 continue
716 }
717 topIn := false
718 if top != "" {
719 _, _, topIn = s.inShare(top)
720 }
721 for _, hp := range hops(hooks) {
722 _, rel, ok := s.inShare(hp)
723 if !ok || rel != "." && mounts.UnderName(rel, nil) {
724 continue
725 }
726 // Named from the top of the repository, even across a writable
727 // volume inside it: husky's .husky/_ calls .husky/<hook>.
728 inRepo := rel
729 if topIn {
730 if r, ok := paths.In(hp, top); ok {
731 inRepo = r
732 }
733 }
734 // A name only covers what is below it in the share the VM
735 // writes through.
736 if n, ok := HooksName(inRepo); ok && !mounts.UnderName(rel, []string{n}) {
737 inRepo = "."
738 }
739 if strings.IndexFunc(inRepo, unprintable) >= 0 {
740 inRepo = ""
741 }
742 shown := s.shown(hp)
743 s.emit(visible(shown) + "\t" + inRepo)
744 }
745 }
746 for i, r := range rs {
747 s.config(r.kind, r.at, tops[i])
748 // A hook linked to a file a share holds: git runs that file, which
749 // may be outside every name.
750 if hookss[i] == "" {
751 continue
752 }
753 hp, ok := Spelling(hookss[i])
754 if !ok {
755 continue
756 }
757 // As the shell's "$hp"/*: no dotfiles.
758 ents, err := os.ReadDir(hp)
759 if err != nil {
760 s.unchecked("the hooks", hp, err)
761 }
762 for _, e := range ents {
763 f := hp + "/" + e.Name()
764 if strings.HasPrefix(e.Name(), ".") || strings.HasSuffix(f, ".sample") {
765 continue
766 }
767 if e.Type().IsRegular() {
768 // Another name for the file may be in a share: the VM writes
769 // the file through it, whatever .git says.
770 if linked(f) {
771 s.risk(risk{text: "hook " + e.Name() + " has other hard links: one may be in a share"})
772 }
773 continue
774 }
775 if e.Type()&fs.ModeSymlink == 0 {
776 continue
777 }
778 t, err := os.Readlink(f)
779 if err != nil {
780 s.unchecked("the hook "+e.Name(), hp, err)
781 continue
782 }
783 s.risk(risk{prefix: "hook " + e.Name() + " runs ", hops: s.hits(gitAbs(filepath.ToSlash(t), hp))})
784 }
785 }
786 return &Result{Hooks: s.hooks, risks: s.risks}
787}
788
789// HooksName is the name that keeps the hooks folder rel read-only: its
790// first component, which covers the folder and what it calls next to it
791// (husky's hooks call .husky/<hook>). False for the project itself, and for
792// a name the shares cannot carry.
793func HooksName(rel string) (string, bool) {
794 name, _, _ := strings.Cut(rel, "/")
795 // Nothing JSON would escape on its way into Lima's config either.
796 if rel == "." || name == "" || strings.ContainsAny(name, "\"\\\u2028\u2029") || strings.IndexFunc(name, unprintable) >= 0 || !utf8.ValidString(name) {
797 return "", false
798 }
799 return name, true
800}