Debian Codegraph @

common/hexec/exec.go

raw
1 // Copyright 2026 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hexec
15
16 import (
17 "bufio"
18 "bytes"
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "os"
24 "os/exec"
25 "path/filepath"
26 "regexp"
27 "slices"
28 "strings"
29
30 "github.com/bep/logg"
31 "github.com/gohugoio/hugo/common/hmaps"
32 "github.com/gohugoio/hugo/common/loggers"
33 "github.com/gohugoio/hugo/config"
34 "github.com/gohugoio/hugo/config/security"
35 )
36
37 var WithDir = func(dir string) func(c *commandeer) {
38 return func(c *commandeer) {
39 c.dir = dir
40 }
41 }
42
43 var WithContext = func(ctx context.Context) func(c *commandeer) {
44 return func(c *commandeer) {
45 c.ctx = ctx
46 }
47 }
48
49 var WithStdout = func(w io.Writer) func(c *commandeer) {
50 return func(c *commandeer) {
51 c.stdout = w
52 }
53 }
54
55 var WithStderr = func(w io.Writer) func(c *commandeer) {
56 return func(c *commandeer) {
57 c.stderr = w
58 }
59 }
60
61 var WithStdin = func(r io.Reader) func(c *commandeer) {
62 return func(c *commandeer) {
63 c.stdin = r
64 }
65 }
66
67 var WithEnviron = func(env []string) func(c *commandeer) {
68 return func(c *commandeer) {
69 setOrAppend := func(s string) {
70 k1, _ := config.SplitEnvVar(s)
71 var found bool
72 for i, v := range c.env {
73 k2, _ := config.SplitEnvVar(v)
74 if k1 == k2 {
75 found = true
76 c.env[i] = s
77 }
78 }
79
80 if !found {
81 c.env = append(c.env, s)
82 }
83 }
84
85 for _, s := range env {
86 setOrAppend(s)
87 }
88 }
89 }
90
91 // New creates a new Exec using the provided security config.
92 func New(cfg security.Config, workingDir string, log loggers.Logger) *Exec {
93 var baseEnviron []string
94 for _, v := range os.Environ() {
95 k, _ := config.SplitEnvVar(v)
96 if cfg.Exec.OsEnv.Accept(k) {
97 baseEnviron = append(baseEnviron, v)
98 }
99 }
100
101 return &Exec{
102 sc: cfg,
103 workingDir: workingDir,
104 infol: log.InfoCommand("exec"),
105 baseEnviron: baseEnviron,
106 nodeRunnerCache: hmaps.NewCache[string, func(arg ...any) (Runner, error)](),
107 nodeSymlinkChecks: hmaps.NewCache[string, bool](),
108 readPathChecks: hmaps.NewCacheWithOptions[string, bool](hmaps.CacheOptions{Size: 10000}),
109 }
110 }
111
112 // IsNotFound reports whether this is an error about a binary not found.
113 func IsNotFound(err error) bool {
114 var notFoundErr *NotFoundError
115 return errors.As(err, &notFoundErr)
116 }
117
118 // Exec enforces a security policy for commands run via os/exec.
119 type Exec struct {
120 sc security.Config
121 workingDir string
122 infol logg.LevelLogger
123
124 // os.Environ filtered by the Exec.OsEnviron whitelist filter.
125 baseEnviron []string
126
127 // Additional absolute paths to allow reading from in the Node.js permission model.
128 nodeReadPaths []string
129
130 nodeRunnerCache *hmaps.Cache[string, func(arg ...any) (Runner, error)]
131
132 // Roots already scanned by checkNodeSymlinks, keyed by kind and path.
133 nodeSymlinkChecks *hmaps.Cache[string, bool]
134
135 // Filenames already accepted by CheckReadPath.
136 readPathChecks *hmaps.Cache[string, bool]
137 }
138
139 // SetNodeReadPaths sets additional absolute paths to allow reading from
140 // in the Node.js permission model (e.g. Hugo module cache directories).
141 func (e *Exec) SetNodeReadPaths(paths []string) {
142 e.nodeReadPaths = paths
143 }
144
145 func (e *Exec) New(name string, arg ...any) (Runner, error) {
146 return e.new(name, "", arg...)
147 }
148
149 // New will fail if name is not allowed according to the configured security policy.
150 // Else a configured Runner will be returned ready to be Run.
151 func (e *Exec) new(name string, fullyQualifiedName string, arg ...any) (Runner, error) {
152 if err := e.sc.CheckAllowedExec(name); err != nil {
153 return nil, err
154 }
155
156 env := make([]string, len(e.baseEnviron))
157 copy(env, e.baseEnviron)
158
159 cm := &commandeer{
160 name: name,
161 fullyQualifiedName: fullyQualifiedName,
162 env: env,
163 }
164
165 return cm.command(arg...)
166 }
167
168 type binaryLocation int
169
170 func (b binaryLocation) String() string {
171 switch b {
172 case binaryLocationNodeModules:
173 return "node_modules/.bin"
174 case binaryLocationPath:
175 return "PATH"
176 }
177 return "unknown"
178 }
179
180 const (
181 binaryLocationNodeModules binaryLocation = iota + 1
182 binaryLocationPath
183 )
184
185 // Npx finds and runs a Node.js tool. The binary is located first in
186 // WORKINGDIR/node_modules/.bin, then in PATH. The tool is always invoked via
187 // "node [--permission <flags>] <script> <args>"; the --permission flags are
188 // added when the Node.js permission model is enabled.
189 func (e *Exec) Npx(name string, arg ...any) (Runner, error) {
190 if err := e.sc.CheckAllowedExec(name); err != nil {
191 return nil, err
192 }
193 if err := e.sc.CheckAllowedExec("node"); err != nil {
194 // Legacy path: We replaced npx with node in v0.161.0, and anyone using these tools with a custom security.exec.allow list
195 // would get an error when upgrading. To avoid this, check for npx as well.
196 if err2 := e.sc.CheckAllowedExec("npx"); err2 != nil {
197 return nil, err
198 }
199 }
200
201 newRunner, err := e.nodeRunnerCache.GetOrCreate(name, func() (func(...any) (Runner, error), error) {
202 var resolvedBin string
203 var loc binaryLocation
204
205 nodeBinFilename := filepath.Join(e.workingDir, nodeModulesBinPath, name)
206 if p, err := exec.LookPath(nodeBinFilename); err == nil {
207 resolvedBin = p
208 loc = binaryLocationNodeModules
209 } else if p, err := exec.LookPath(name); err == nil {
210 resolvedBin = p
211 loc = binaryLocationPath
212 } else {
213 return nil, &NotFoundError{name: name, method: "in PATH"}
214 }
215
216 scriptPath := resolveNodeBin(resolvedBin)
217
218 e.infol.WithFields(logg.Fields{
219 logg.Field{Name: "location", Value: loc},
220 logg.Field{Name: "bin", Value: resolvedBin},
221 logg.Field{Name: "script", Value: scriptPath},
222 }).Logf("resolve %q", name)
223
224 if scriptPath == "" {
225 return nil, fmt.Errorf("binary %q is not a Node.js script", name)
226 }
227
228 return func(arg2 ...any) (Runner, error) {
229 return e.newNode(name, scriptPath, arg2...)
230 }, nil
231 })
232 if err != nil {
233 return nil, err
234 }
235
236 return newRunner(arg...)
237 }
238
239 // newNode runs a Node.js script via "node [--permission <flags>] <scriptPath> <args>".
240 func (e *Exec) newNode(name, scriptPath string, arg ...any) (Runner, error) {
241 if e.sc.Node.Permissions.IsEnabled() {
242 if err := e.checkNodeSymlinks("allowRead", e.nodeReadRoots(scriptPath)); err != nil {
243 return nil, err
244 }
245 if err := e.checkNodeSymlinks("allowWrite", e.nodeWriteRoots()); err != nil {
246 return nil, err
247 }
248 }
249
250 var allArgs []any
251 for _, pa := range e.nodePermissionArgs(name, scriptPath) {
252 allArgs = append(allArgs, pa)
253 }
254 // Install an ESM resolver hook that makes NODE_PATH a fallback for failed
255 // bare imports, so postcss.config.js / babel.config.js / etc. written in
256 // ESM work when loaded from the Hugo module cache. See esmloader.mjs.
257 allArgs = append(allArgs, nodeESMLoaderImportArg())
258 allArgs = append(allArgs, scriptPath)
259 allArgs = append(allArgs, arg...)
260 // When the script lives outside the working dir (a globally installed
261 // tool), point NODE_PATH at the script's node_modules ancestor so Node's
262 // resolver (and tools that honor it, e.g. tailwindcss v4) can locate the
263 // tool's sibling packages. tailwindcss v4's CSS resolver treats NODE_PATH
264 // as a single path, not a list, so we don't concatenate with the local
265 // path here. For local installs the caller's NODE_PATH (set by
266 // hugo.GetExecEnviron to <workDir>/node_modules) already covers the need.
267 localNM := filepath.Join(e.workingDir, "node_modules")
268 if p := nodeScriptReadPath(scriptPath); p != "" && p != localNM {
269 allArgs = append(allArgs, WithEnviron([]string{"NODE_PATH=" + p}))
270 }
271
272 return e.New("node", allArgs...)
273 }
274
275 // nodePermissionArgs builds the Node.js --permission flags from the security config.
276 func (e *Exec) nodePermissionArgs(name, scriptPath string) []string {
277 perms := e.sc.Node.Permissions
278 if !perms.IsEnabled() {
279 return nil
280 }
281
282 args := []string{"--permission"}
283
284 for _, p := range e.nodeReadRoots(scriptPath) {
285 args = append(args, "--allow-fs-read="+p)
286 }
287 for _, p := range e.nodeWriteRoots() {
288 args = append(args, "--allow-fs-write="+p)
289 }
290
291 var silenceSecurityWarnings bool
292 if slices.Contains(perms.AllowAddons, name) {
293 silenceSecurityWarnings = true
294 args = append(args, "--allow-addons")
295 }
296
297 if slices.Contains(perms.AllowWorker, name) {
298 silenceSecurityWarnings = true
299 args = append(args, "--allow-worker")
300 }
301
302 if slices.Contains(perms.AllowChildProcess, name) {
303 silenceSecurityWarnings = true
304 args = append(args, "--allow-child-process")
305 }
306
307 if silenceSecurityWarnings {
308 // There are no more fine grained way to do this, see https://github.com/nodejs/node/issues/59818
309 // If the process is configured to allow either workers or addons, Node will print warnings that's not very helpful.
310 args = append(args, "--disable-warning=SecurityWarning")
311 }
312
313 return args
314 }
315
316 func (e *Exec) nodeReadRoots(scriptPath string) []string {
317 roots := e.resolveNodePermPaths(e.sc.Node.Permissions.AllowRead)
318 roots = append(roots, e.nodeReadPaths...)
319 if p := nodeScriptReadPath(scriptPath); p != "" {
320 roots = append(roots, p)
321 }
322 return roots
323 }
324
325 func (e *Exec) nodeWriteRoots() []string {
326 return e.resolveNodePermPaths(e.sc.Node.Permissions.AllowWrite)
327 }
328
329 // resolveNodePermPaths resolves relative paths against the working directory.
330 func (e *Exec) resolveNodePermPaths(paths []string) []string {
331 resolved := make([]string, len(paths))
332 for i, p := range paths {
333 switch {
334 case p == "*":
335 resolved[i] = "*"
336 case filepath.IsAbs(p):
337 resolved[i] = p
338 default:
339 resolved[i] = filepath.Join(e.workingDir, p)
340 }
341 }
342 return resolved
343 }
344
345 const nodeModulesBinPath = "node_modules/.bin"
346
347 // nodeScriptReadPath returns a path to add to the Node.js read allow-list so
348 // a script can load its dependencies. For scripts inside a node_modules tree
349 // it returns the nearest ancestor "node_modules" directory, so both nested
350 // and hoisted deps are reachable. Otherwise the script's own directory.
351 func nodeScriptReadPath(scriptPath string) string {
352 if scriptPath == "" {
353 return ""
354 }
355 dir := filepath.Dir(scriptPath)
356 for {
357 if filepath.Base(dir) == "node_modules" {
358 return dir
359 }
360 parent := filepath.Dir(dir)
361 if parent == dir {
362 return filepath.Dir(scriptPath)
363 }
364 dir = parent
365 }
366 }
367
368 // resolveNodeBin resolves a binary path to the underlying Node.js script.
369 // Returns the path to the JS entry point, or "" if the binary is not a Node script.
370 func resolveNodeBin(path string) string {
371 // 1. If the file is a symlink, resolve it (macOS/Linux npm creates symlinks in node_modules/.bin).
372 if info, err := os.Lstat(path); err == nil && info.Mode()&os.ModeSymlink != 0 {
373 if resolved, err := filepath.EvalSymlinks(path); err == nil {
374 if hasJSExtension(resolved) || isNodeScript(resolved) {
375 return resolved
376 }
377 }
378 return ""
379 }
380 // 2. Check if the file itself is a Node script (e.g. globally installed with #!/usr/bin/env node).
381 if isNodeScript(path) {
382 return path
383 }
384 // 3. Try extracting JS entry point from an npm wrapper script (.cmd or shell).
385 return extractNodeEntryPoint(path)
386 }
387
388 // nodeEntryPointRe matches a relative path in npm-generated wrapper scripts.
389 // The entry may be a .js/.mjs/.cjs file or an extensionless Node shebang
390 // script (e.g. postcss-cli 7's bin/postcss). Local installs reference the
391 // entry via "..", global installs via "node_modules" (notably on Windows,
392 // where npm does not symlink global binaries).
393 // Examples:
394 //
395 // Local shell: "$basedir/../postcss-cli/index.js"
396 // Local cmd: "%dp0%\..\postcss-cli\index.js"
397 // Scoped: "$basedir/../@babel/cli/bin/babel.js"
398 // No ext: "%dp0%\..\postcss-cli\bin\postcss"
399 // Global shell: "$basedir/node_modules/postcss-cli/index.js"
400 // Global cmd: "%dp0%\node_modules\postcss-cli\index.js"
401 var nodeEntryPointRe = regexp.MustCompile(`[/\\]((?:\.\.|node_modules)[/\\][\w@][\w@./\\-]*)`)
402
403 // extractNodeEntryPoint reads an npm wrapper script and extracts the Node
404 // entry point path, validating that it's a JS file or a Node shebang script.
405 func extractNodeEntryPoint(wrapperPath string) string {
406 data, err := os.ReadFile(wrapperPath)
407 if err != nil {
408 return ""
409 }
410 m := nodeEntryPointRe.FindSubmatch(data)
411 if m == nil {
412 return ""
413 }
414 // Normalize backslashes from Windows .cmd wrappers.
415 relPath := strings.ReplaceAll(string(m[1]), "\\", "/")
416 resolved := filepath.Join(filepath.Dir(wrapperPath), relPath)
417 if _, err := os.Stat(resolved); err != nil {
418 return ""
419 }
420 if !hasJSExtension(resolved) && !isNodeScript(resolved) {
421 return ""
422 }
423 return resolved
424 }
425
426 func hasJSExtension(path string) bool {
427 switch filepath.Ext(path) {
428 case ".js", ".mjs", ".cjs":
429 return true
430 }
431 return false
432 }
433
434 // isNodeScript reports whether the file at path has a Node.js shebang.
435 func isNodeScript(path string) bool {
436 f, err := os.Open(path)
437 if err != nil {
438 return false
439 }
440 defer f.Close()
441 r := bufio.NewReader(f)
442 line, err := r.ReadString('\n')
443 if err != nil && len(line) == 0 {
444 return false
445 }
446 return strings.HasPrefix(line, "#!") && strings.Contains(line, "node")
447 }
448
449 // Sec returns the security policies this Exec is configured with.
450 func (e *Exec) Sec() security.Config {
451 return e.sc
452 }
453
454 type NotFoundError struct {
455 name string
456 method string
457 }
458
459 func (e *NotFoundError) Error() string {
460 return fmt.Sprintf("binary with name %q not found %s", e.name, e.method)
461 }
462
463 // Runner wraps a *os.Cmd.
464 type Runner interface {
465 Run() error
466 StdinPipe() (io.WriteCloser, error)
467 }
468
469 type cmdWrapper struct {
470 name string
471 c *exec.Cmd
472
473 outerr *bytes.Buffer
474 }
475
476 var notFoundRe = regexp.MustCompile(`(?s)not found:|could not determine executable`)
477
478 func (c *cmdWrapper) Run() error {
479 err := c.c.Run()
480 if err == nil {
481 return nil
482 }
483 if notFoundRe.MatchString(c.outerr.String()) {
484 return &NotFoundError{name: c.name, method: "in PATH"}
485 }
486 return fmt.Errorf("failed to execute binary %q with args %v: %s", c.name, c.c.Args[1:], c.outerr.String())
487 }
488
489 func (c *cmdWrapper) StdinPipe() (io.WriteCloser, error) {
490 return c.c.StdinPipe()
491 }
492
493 type commandeer struct {
494 stdout io.Writer
495 stderr io.Writer
496 stdin io.Reader
497 dir string
498 ctx context.Context
499
500 name string
501 fullyQualifiedName string
502 env []string
503 }
504
505 func (c *commandeer) command(arg ...any) (*cmdWrapper, error) {
506 if c == nil {
507 return nil, nil
508 }
509
510 var args []string
511 for _, a := range arg {
512 switch v := a.(type) {
513 case string:
514 args = append(args, v)
515 case func(*commandeer):
516 v(c)
517 default:
518 return nil, fmt.Errorf("invalid argument to command: %T", a)
519 }
520 }
521
522 var bin string
523 if c.fullyQualifiedName != "" {
524 bin = c.fullyQualifiedName
525 } else {
526 var err error
527 bin, err = exec.LookPath(c.name)
528 if err != nil {
529 return nil, &NotFoundError{
530 name: c.name,
531 method: "in PATH",
532 }
533 }
534 }
535
536 outerr := &bytes.Buffer{}
537 if c.stderr == nil {
538 c.stderr = outerr
539 } else {
540 c.stderr = io.MultiWriter(c.stderr, outerr)
541 }
542
543 var cmd *exec.Cmd
544
545 if c.ctx != nil {
546 cmd = exec.CommandContext(c.ctx, bin, args...)
547 } else {
548 cmd = exec.Command(bin, args...)
549 }
550
551 cmd.Stdin = c.stdin
552 cmd.Stderr = c.stderr
553 cmd.Stdout = c.stdout
554 cmd.Env = c.env
555 cmd.Dir = c.dir
556
557 return &cmdWrapper{outerr: outerr, c: cmd, name: c.name}, nil
558 }
559
560 // InPath reports whether binaryName is in $PATH.
561 func InPath(binaryName string) bool {
562 if strings.Contains(binaryName, "/") {
563 panic("binary name should not contain any slash")
564 }
565 _, err := exec.LookPath(binaryName)
566 return err == nil
567 }
568
569 // LookPath finds the path to binaryName in $PATH.
570 // Returns "" if not found.
571 func LookPath(binaryName string) string {
572 if strings.Contains(binaryName, "/") {
573 panic("binary name should not contain any slash")
574 }
575 s, err := exec.LookPath(binaryName)
576 if err != nil {
577 return ""
578 }
579 return s
580 }