Debian Codegraph @

common/hexec/exec_test.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 "os"
18 "path/filepath"
19 "runtime"
20 "testing"
21
22 qt "github.com/frankban/quicktest"
23 "github.com/gohugoio/hugo/config/security"
24 )
25
26 func TestNodePermissionArgs(t *testing.T) {
27 c := qt.New(t)
28
29 // Use t.TempDir() so paths are absolute on any OS (avoids Windows volume assumptions).
30 base := t.TempDir()
31 site := filepath.Join(base, "site")
32 tmp := filepath.Join(base, "tmp")
33 cacheDir := filepath.Join(base, "home", "user", ".cache", "hugo_cache", "modules")
34
35 c.Run("Default config tailwindcss", func(c *qt.C) {
36 e := &Exec{
37 sc: security.DefaultConfig,
38 workingDir: site,
39 }
40 args := e.nodePermissionArgs("tailwindcss", "")
41 c.Assert(args, qt.DeepEquals, []string{
42 "--permission",
43 "--allow-fs-read=" + site,
44 "--allow-addons",
45 "--allow-worker",
46 "--allow-child-process",
47 "--disable-warning=SecurityWarning",
48 })
49 })
50
51 c.Run("Default config postcss", func(c *qt.C) {
52 e := &Exec{
53 sc: security.DefaultConfig,
54 workingDir: site,
55 }
56 args := e.nodePermissionArgs("postcss", "")
57 c.Assert(args, qt.DeepEquals, []string{
58 "--permission",
59 "--allow-fs-read=" + site,
60 })
61 })
62
63 c.Run("Multiple paths", func(c *qt.C) {
64 cfg := security.DefaultConfig
65 cfg.Node.Permissions.AllowRead = []string{".", tmp}
66 cfg.Node.Permissions.AllowWrite = []string{"."}
67 e := &Exec{
68 sc: cfg,
69 workingDir: site,
70 }
71 args := e.nodePermissionArgs("tailwindcss", "")
72 c.Assert(args, qt.DeepEquals, []string{
73 "--permission",
74 "--allow-fs-read=" + site,
75 "--allow-fs-read=" + tmp,
76 "--allow-fs-write=" + site,
77 "--allow-addons",
78 "--allow-worker",
79 "--allow-child-process",
80 "--disable-warning=SecurityWarning",
81 })
82 })
83
84 c.Run("Wildcard", func(c *qt.C) {
85 cfg := security.DefaultConfig
86 cfg.Node.Permissions.AllowRead = []string{"*"}
87 cfg.Node.Permissions.AllowWrite = []string{"*"}
88 e := &Exec{
89 sc: cfg,
90 workingDir: site,
91 }
92 args := e.nodePermissionArgs("tailwindcss", "")
93 c.Assert(args, qt.DeepEquals, []string{
94 "--permission",
95 "--allow-fs-read=*",
96 "--allow-fs-write=*",
97 "--allow-addons",
98 "--allow-worker",
99 "--allow-child-process",
100 "--disable-warning=SecurityWarning",
101 })
102 })
103
104 c.Run("Disabled", func(c *qt.C) {
105 cfg := security.DefaultConfig
106 cfg.Node.Permissions.Disable = true
107 e := &Exec{
108 sc: cfg,
109 workingDir: site,
110 }
111 args := e.nodePermissionArgs("tailwindcss", "")
112 c.Assert(args, qt.IsNil)
113 })
114
115 c.Run("No fs flags", func(c *qt.C) {
116 cfg := security.DefaultConfig
117 cfg.Node.Permissions.AllowRead = nil
118 cfg.Node.Permissions.AllowAddons = nil
119 cfg.Node.Permissions.AllowWorker = nil
120 cfg.Node.Permissions.AllowChildProcess = nil
121 e := &Exec{
122 sc: cfg,
123 workingDir: site,
124 }
125 args := e.nodePermissionArgs("postcss", "")
126 c.Assert(args, qt.DeepEquals, []string{"--permission"})
127 })
128
129 c.Run("Read only", func(c *qt.C) {
130 cfg := security.DefaultConfig
131 cfg.Node.Permissions.AllowRead = []string{"."}
132 cfg.Node.Permissions.AllowWrite = nil
133 e := &Exec{
134 sc: cfg,
135 workingDir: site,
136 }
137 args := e.nodePermissionArgs("postcss", "")
138 c.Assert(args, qt.DeepEquals, []string{
139 "--permission",
140 "--allow-fs-read=" + site,
141 })
142 })
143
144 c.Run("With additional read paths", func(c *qt.C) {
145 e := &Exec{
146 sc: security.DefaultConfig,
147 workingDir: site,
148 nodeReadPaths: []string{cacheDir},
149 }
150 args := e.nodePermissionArgs("postcss", "")
151 c.Assert(args, qt.DeepEquals, []string{
152 "--permission",
153 "--allow-fs-read=" + site,
154 "--allow-fs-read=" + cacheDir,
155 })
156 })
157
158 c.Run("Global install script path", func(c *qt.C) {
159 e := &Exec{
160 sc: security.DefaultConfig,
161 workingDir: site,
162 }
163 globalNM := filepath.Join(base, "nvm", "lib", "node_modules")
164 script := filepath.Join(globalNM, "postcss-cli", "bin", "postcss")
165 args := e.nodePermissionArgs("postcss", script)
166 c.Assert(args, qt.DeepEquals, []string{
167 "--permission",
168 "--allow-fs-read=" + site,
169 "--allow-fs-read=" + globalNM,
170 })
171 })
172 }
173
174 func TestNodeScriptReadPath(t *testing.T) {
175 c := qt.New(t)
176
177 base := t.TempDir()
178 nm := filepath.Join(base, "node_modules")
179 globalNM := filepath.Join(base, "nvm", "lib", "node_modules")
180
181 c.Assert(nodeScriptReadPath(""), qt.Equals, "")
182 c.Assert(nodeScriptReadPath(filepath.Join(nm, "postcss-cli", "index.js")), qt.Equals, nm)
183 c.Assert(nodeScriptReadPath(filepath.Join(nm, "@babel", "cli", "bin", "babel.js")), qt.Equals, nm)
184 c.Assert(nodeScriptReadPath(filepath.Join(globalNM, "postcss-cli", "bin", "postcss")), qt.Equals, globalNM)
185
186 loose := filepath.Join(base, "tools", "script.js")
187 c.Assert(nodeScriptReadPath(loose), qt.Equals, filepath.Dir(loose))
188 }
189
190 func TestResolveNodeBin(t *testing.T) {
191 c := qt.New(t)
192
193 // Create a fake node_modules structure.
194 dir := t.TempDir()
195 nodeModules := filepath.Join(dir, "node_modules")
196 binDir := filepath.Join(nodeModules, ".bin")
197
198 // Create target JS files.
199 postcssJS := filepath.Join(nodeModules, "postcss-cli", "index.js")
200 babelJS := filepath.Join(nodeModules, "@babel", "cli", "bin", "babel.js")
201 mkdirAndWrite(t, postcssJS, "#!/usr/bin/env node\nconsole.log('postcss');\n")
202 mkdirAndWrite(t, babelJS, "#!/usr/bin/env node\nconsole.log('babel');\n")
203 os.MkdirAll(binDir, 0o755)
204
205 c.Run("Symlink to JS file", func(c *qt.C) {
206 if runtime.GOOS == "windows" {
207 c.Skip("Symlinks may require elevated privileges on Windows")
208 }
209 link := filepath.Join(binDir, "postcss-link")
210 os.Remove(link)
211 c.Assert(os.Symlink(postcssJS, link), qt.IsNil)
212
213 resolved := resolveNodeBin(link)
214 t.Logf("Symlink: link=%q, resolved=%q", link, resolved)
215 c.Assert(resolved, qt.Not(qt.Equals), "")
216 c.Assert(sameFile(t, resolved, postcssJS), qt.IsTrue)
217 })
218
219 c.Run("Symlink to scoped package", func(c *qt.C) {
220 if runtime.GOOS == "windows" {
221 c.Skip("Symlinks may require elevated privileges on Windows")
222 }
223 link := filepath.Join(binDir, "babel-link")
224 os.Remove(link)
225 c.Assert(os.Symlink(babelJS, link), qt.IsNil)
226
227 resolved := resolveNodeBin(link)
228 t.Logf("Scoped symlink: link=%q, resolved=%q", link, resolved)
229 c.Assert(resolved, qt.Not(qt.Equals), "")
230 c.Assert(sameFile(t, resolved, babelJS), qt.IsTrue)
231 })
232
233 c.Run("Shell wrapper", func(c *qt.C) {
234 wrapper := filepath.Join(binDir, "postcss-sh")
235 content := "#!/bin/sh\n" +
236 `basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")` + "\n" +
237 `exec node "$basedir/../postcss-cli/index.js" "$@"` + "\n"
238 mkdirAndWrite(t, wrapper, content)
239
240 resolved := resolveNodeBin(wrapper)
241 t.Logf("Shell wrapper: wrapper=%q, resolved=%q", wrapper, resolved)
242 c.Assert(resolved, qt.Not(qt.Equals), "")
243 c.Assert(sameFile(t, resolved, postcssJS), qt.IsTrue)
244 })
245
246 c.Run("Cmd wrapper", func(c *qt.C) {
247 wrapper := filepath.Join(binDir, "postcss.cmd")
248 content := "@ECHO off\r\n" +
249 "SETLOCAL\r\n" +
250 `endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\postcss-cli\index.js" %*` + "\r\n"
251 mkdirAndWrite(t, wrapper, content)
252
253 resolved := resolveNodeBin(wrapper)
254 t.Logf("Cmd wrapper: wrapper=%q, resolved=%q", wrapper, resolved)
255 c.Assert(resolved, qt.Not(qt.Equals), "")
256 c.Assert(sameFile(t, resolved, postcssJS), qt.IsTrue)
257 })
258
259 c.Run("Cmd wrapper scoped package", func(c *qt.C) {
260 wrapper := filepath.Join(binDir, "babel.cmd")
261 content := "@ECHO off\r\n" +
262 `endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\@babel\cli\bin\babel.js" %*` + "\r\n"
263 mkdirAndWrite(t, wrapper, content)
264
265 resolved := resolveNodeBin(wrapper)
266 t.Logf("Cmd wrapper (scoped): wrapper=%q, resolved=%q", wrapper, resolved)
267 c.Assert(resolved, qt.Not(qt.Equals), "")
268 c.Assert(sameFile(t, resolved, babelJS), qt.IsTrue)
269 })
270
271 c.Run("Node script with shebang", func(c *qt.C) {
272 script := filepath.Join(binDir, "node-global")
273 mkdirAndWrite(t, script, "#!/usr/bin/env node\nconsole.log('global');\n")
274
275 resolved := resolveNodeBin(script)
276 t.Logf("Node script: path=%q, resolved=%q", script, resolved)
277 c.Assert(resolved, qt.Equals, script)
278 })
279
280 c.Run("Native binary", func(c *qt.C) {
281 native := filepath.Join(binDir, "native-tool")
282 mkdirAndWrite(t, native, "\x7fELF\x00\x00\x00")
283
284 resolved := resolveNodeBin(native)
285 t.Logf("Native binary: path=%q, resolved=%q", native, resolved)
286 c.Assert(resolved, qt.Equals, "")
287 })
288
289 c.Run("Nonexistent file", func(c *qt.C) {
290 c.Assert(resolveNodeBin("/nonexistent/path"), qt.Equals, "")
291 })
292
293 c.Run("Wrapper with missing target", func(c *qt.C) {
294 wrapper := filepath.Join(binDir, "missing-target")
295 mkdirAndWrite(t, wrapper, "#!/bin/sh\nexec node \"$basedir/../no-such-pkg/index.js\" \"$@\"\n")
296
297 resolved := resolveNodeBin(wrapper)
298 t.Logf("Missing target: wrapper=%q, resolved=%q", wrapper, resolved)
299 c.Assert(resolved, qt.Equals, "")
300 })
301 }
302
303 func TestExtractNodeEntryPointRegex(t *testing.T) {
304 c := qt.New(t)
305
306 cases := []struct {
307 name string
308 content string
309 want string // expected capture group (with original separators)
310 }{
311 {"shell postcss", `"$basedir/../postcss-cli/index.js"`, "../postcss-cli/index.js"},
312 {"shell babel", `"$basedir/../@babel/cli/bin/babel.js"`, "../@babel/cli/bin/babel.js"},
313 {"shell tailwind mjs", `"$basedir/../@tailwindcss/cli/dist/index.mjs"`, "../@tailwindcss/cli/dist/index.mjs"},
314 {"cmd postcss", `"%dp0%\..\postcss-cli\index.js"`, `..\postcss-cli\index.js`},
315 {"cmd babel", `"%dp0%\..\@babel\cli\bin\babel.js"`, `..\@babel\cli\bin\babel.js`},
316 {"cmd postcss no ext", `"%dp0%\..\postcss-cli\bin\postcss"`, `..\postcss-cli\bin\postcss`},
317 {"shell postcss no ext", `"$basedir/../postcss-cli/bin/postcss"`, "../postcss-cli/bin/postcss"},
318 {"cmd postcss global", `"%dp0%\node_modules\postcss-cli\index.js"`, `node_modules\postcss-cli\index.js`},
319 {"cmd babel global", `"%dp0%\node_modules\@babel\cli\bin\babel.js"`, `node_modules\@babel\cli\bin\babel.js`},
320 {"shell postcss global", `"$basedir/node_modules/postcss-cli/index.js"`, "node_modules/postcss-cli/index.js"},
321 }
322
323 for _, tc := range cases {
324 c.Run(tc.name, func(c *qt.C) {
325 m := nodeEntryPointRe.FindStringSubmatch(tc.content)
326 t.Logf("regex match for %q: %v", tc.name, m)
327 c.Assert(m, qt.Not(qt.IsNil))
328 c.Assert(m[1], qt.Equals, tc.want)
329 })
330 }
331
332 c.Run("No match", func(c *qt.C) {
333 for _, s := range []string{"@ECHO off", "#!/bin/bash\necho hello", "\x7fELF"} {
334 c.Assert(nodeEntryPointRe.FindStringSubmatch(s), qt.IsNil)
335 }
336 })
337 }
338
339 // TestResolveNodeBinWindows tests wrapper resolution on all platforms
340 // by simulating Windows-style wrapper files. On Windows CI, this also
341 // tests the native .cmd resolution path.
342 func TestResolveNodeBinWindows(t *testing.T) {
343 c := qt.New(t)
344
345 dir := t.TempDir()
346 nodeModules := filepath.Join(dir, "node_modules")
347 binDir := filepath.Join(nodeModules, ".bin")
348
349 // Create target JS file.
350 targetJS := filepath.Join(nodeModules, "postcss-cli", "index.js")
351 mkdirAndWrite(t, targetJS, "#!/usr/bin/env node\nconsole.log('postcss');\n")
352 os.MkdirAll(binDir, 0o755)
353
354 // Simulate what npm creates on Windows: a .cmd wrapper and a shell script.
355 cmdWrapper := filepath.Join(binDir, "postcss.cmd")
356 cmdContent := "@ECHO off\r\n" +
357 "SETLOCAL\r\n" +
358 "CALL :find_dp0\r\n" +
359 `endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\postcss-cli\index.js" %*` + "\r\n"
360 mkdirAndWrite(t, cmdWrapper, cmdContent)
361
362 shWrapper := filepath.Join(binDir, "postcss")
363 shContent := "#!/bin/sh\n" +
364 `exec node "$basedir/../postcss-cli/index.js" "$@"` + "\n"
365 mkdirAndWrite(t, shWrapper, shContent)
366
367 t.Logf("GOOS=%s", runtime.GOOS)
368 t.Logf("cmd wrapper: %s", cmdWrapper)
369 t.Logf("sh wrapper: %s", shWrapper)
370 t.Logf("target JS: %s", targetJS)
371
372 c.Run("cmd wrapper resolves to JS", func(c *qt.C) {
373 resolved := resolveNodeBin(cmdWrapper)
374 t.Logf("resolveNodeBin(%q) = %q", cmdWrapper, resolved)
375 c.Assert(resolved, qt.Not(qt.Equals), "")
376 c.Assert(sameFile(t, resolved, targetJS), qt.IsTrue)
377 })
378
379 c.Run("sh wrapper resolves to JS", func(c *qt.C) {
380 resolved := resolveNodeBin(shWrapper)
381 t.Logf("resolveNodeBin(%q) = %q", shWrapper, resolved)
382 c.Assert(resolved, qt.Not(qt.Equals), "")
383 c.Assert(sameFile(t, resolved, targetJS), qt.IsTrue)
384 })
385
386 // Simulate postcss-cli 7, whose wrappers point to an extensionless Node
387 // shebang script (bin/postcss) rather than a .js file.
388 targetNoExt := filepath.Join(nodeModules, "postcss-cli", "bin", "postcss")
389 mkdirAndWrite(t, targetNoExt, "#!/usr/bin/env node\nrequire('../');\n")
390
391 cmdNoExt := filepath.Join(binDir, "postcssne.cmd")
392 mkdirAndWrite(t, cmdNoExt, "@ECHO off\r\n"+
393 `"%dp0%\..\postcss-cli\bin\postcss" %*`+"\r\n")
394
395 shNoExt := filepath.Join(binDir, "postcssne")
396 mkdirAndWrite(t, shNoExt, "#!/bin/sh\n"+
397 `exec node "$basedir/../postcss-cli/bin/postcss" "$@"`+"\n")
398
399 c.Run("cmd wrapper resolves to extensionless script", func(c *qt.C) {
400 resolved := resolveNodeBin(cmdNoExt)
401 t.Logf("resolveNodeBin(%q) = %q", cmdNoExt, resolved)
402 c.Assert(resolved, qt.Not(qt.Equals), "")
403 c.Assert(sameFile(t, resolved, targetNoExt), qt.IsTrue)
404 })
405
406 c.Run("sh wrapper resolves to extensionless script", func(c *qt.C) {
407 resolved := resolveNodeBin(shNoExt)
408 t.Logf("resolveNodeBin(%q) = %q", shNoExt, resolved)
409 c.Assert(resolved, qt.Not(qt.Equals), "")
410 c.Assert(sameFile(t, resolved, targetNoExt), qt.IsTrue)
411 })
412
413 // Simulate `npm install -g` on Windows: the wrapper sits at the npm
414 // global prefix and references node_modules as a child (no `..`).
415 globalDir := filepath.Join(dir, "global")
416 globalTarget := filepath.Join(globalDir, "node_modules", "postcss-cli", "index.js")
417 mkdirAndWrite(t, globalTarget, "#!/usr/bin/env node\nconsole.log('postcss');\n")
418
419 globalCmd := filepath.Join(globalDir, "postcss.cmd")
420 mkdirAndWrite(t, globalCmd, "@ECHO off\r\n"+
421 `endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\node_modules\postcss-cli\index.js" %*`+"\r\n")
422
423 globalSh := filepath.Join(globalDir, "postcss")
424 mkdirAndWrite(t, globalSh, "#!/bin/sh\n"+
425 `exec node "$basedir/node_modules/postcss-cli/index.js" "$@"`+"\n")
426
427 c.Run("global cmd wrapper resolves to JS", func(c *qt.C) {
428 resolved := resolveNodeBin(globalCmd)
429 t.Logf("resolveNodeBin(%q) = %q", globalCmd, resolved)
430 c.Assert(resolved, qt.Not(qt.Equals), "")
431 c.Assert(sameFile(t, resolved, globalTarget), qt.IsTrue)
432 })
433
434 c.Run("global sh wrapper resolves to JS", func(c *qt.C) {
435 resolved := resolveNodeBin(globalSh)
436 t.Logf("resolveNodeBin(%q) = %q", globalSh, resolved)
437 c.Assert(resolved, qt.Not(qt.Equals), "")
438 c.Assert(sameFile(t, resolved, globalTarget), qt.IsTrue)
439 })
440
441 globalScopedTarget := filepath.Join(globalDir, "node_modules", "@babel", "cli", "bin", "babel.js")
442 mkdirAndWrite(t, globalScopedTarget, "#!/usr/bin/env node\nconsole.log('babel');\n")
443 globalScopedCmd := filepath.Join(globalDir, "babel.cmd")
444 mkdirAndWrite(t, globalScopedCmd, "@ECHO off\r\n"+
445 `endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\node_modules\@babel\cli\bin\babel.js" %*`+"\r\n")
446
447 c.Run("global cmd wrapper scoped package", func(c *qt.C) {
448 resolved := resolveNodeBin(globalScopedCmd)
449 t.Logf("resolveNodeBin(%q) = %q", globalScopedCmd, resolved)
450 c.Assert(resolved, qt.Not(qt.Equals), "")
451 c.Assert(sameFile(t, resolved, globalScopedTarget), qt.IsTrue)
452 })
453 }
454
455 func sameFile(t *testing.T, a, b string) bool {
456 t.Helper()
457 infoA, errA := os.Stat(a)
458 infoB, errB := os.Stat(b)
459 if errA != nil || errB != nil {
460 t.Logf("sameFile: stat errors: a=%v, b=%v", errA, errB)
461 return false
462 }
463 return os.SameFile(infoA, infoB)
464 }
465
466 func mkdirAndWrite(t *testing.T, path, content string) {
467 t.Helper()
468 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
469 t.Fatal(err)
470 }
471 if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
472 t.Fatal(err)
473 }
474 }