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