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