From fe7dc0f7ed467e281b98af6df05672a9c2d89a10 Mon Sep 17 00:00:00 2001 From: Halima Date: Fri, 20 Nov 2026 12:20:17 +0100 Subject: [PATCH] Harden generator paths and npm remediation Closes #338 Closes #312 Closes #311 Closes #310 --- ...-sw-129-remediation-and-template-safety.md | 5 + docs/reference/commands.md | 2 +- docs/reference/template-generation.md | 10 +- docs/reference/troubleshooting.md | 2 +- src/commands/test.ts | 12 +- src/generator/template-generation.ts | 210 ++++++++---------- src/generator/template-sources.ts | 162 ++++++++++++++ src/process/npm.ts | 65 ++++++ src/testing/project.ts | 38 +++- tests/generator-file-permissions.test.ts | 112 ++++++++++ tests/generator-path-collisions.test.ts | 128 +++++++++++ tests/generator-symlink-ancestor.test.ts | 94 ++++++++ tests/test-missing-npm-remediation.test.ts | 156 +++++++++++++ 13 files changed, 861 insertions(+), 135 deletions(-) create mode 100644 .changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md create mode 100644 tests/generator-file-permissions.test.ts create mode 100644 tests/generator-path-collisions.test.ts create mode 100644 tests/test-missing-npm-remediation.test.ts diff --git a/.changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md b/.changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md new file mode 100644 index 00000000..562b9180 --- /dev/null +++ b/.changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md @@ -0,0 +1,5 @@ +--- +'@diginodes/stellarforge-cli': patch +--- + +Improve generated-project failure handling and template safety. Missing or non-executable npm launchers now produce runtime-version remediation instead of a generic test failure; template sources reject symlink, filesystem-entry, and Unicode/case-collision hazards before writing; generated POSIX file modes are constrained while executable assets retain execute permission. diff --git a/docs/reference/commands.md b/docs/reference/commands.md index 31b6e562..882b3b1a 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -169,7 +169,7 @@ A string-valued but empty or whitespace-only `scripts.test` is rejected with exi When both are present, the Node.js project test workflow is selected first. -StellarForge does not execute package script text directly. It delegates through npm or Cargo and preserves external-process failures. +StellarForge does not execute package script text directly. It delegates through npm or Cargo and preserves external-process failures. If npm or its supported launcher cannot be started, the failure is reported as a missing/permission-denied runtime prerequisite with the supported versions (`Node.js >=22.13.0 <25`, `npm >=10.9.0`) instead of being reported as a test-script failure. StellarForge never falls back to another package manager or installs tools automatically, and the message does not echo environment values. ### Exit behavior diff --git a/docs/reference/template-generation.md b/docs/reference/template-generation.md index 1274fb66..fdb888da 100644 --- a/docs/reference/template-generation.md +++ b/docs/reference/template-generation.md @@ -7,10 +7,12 @@ StellarForge generates projects from project-controlled template directories onl 1. The project name and final destination are validated before generation. 2. The selected template comes from the controlled template registry. 3. Template contents are rendered into a temporary staging directory located beside the final destination. -4. Every template entry is checked before it is copied. Symbolic links and unsupported filesystem entry types are rejected. -5. Text substitution supports only the allowlisted `projectName` and `templateId` tokens. Unknown tokens fail generation; no expression evaluation is performed. -6. Files containing NUL bytes are treated as binary and copied byte-for-byte without substitution. -7. The completed staging directory is promoted to the final destination only after all template files render successfully. +4. Every template entry is checked before it is copied. The source root is resolved to its real path, each entry must resolve inside that root, and symbolic links and unsupported filesystem entry types are rejected. Dangling, escaping, and internal symlink entries are all refused; no symlink target is copied. +5. Template paths are validated for cross-platform portability before writing. Paths that differ only by Unicode normalization or case folding are rejected on every host, and the error names both relative paths. Distinct non-colliding paths remain supported. +6. Generated POSIX file modes are restricted: regular files use `0644`, files with any source execute bit use `0755`, and directories use `0755`. Setuid, setgid, sticky, and group/world write bits are never copied. On Windows, POSIX mode bits are not meaningful, so generation does not apply chmod and the ordinary writable-file behavior applies. +7. Text substitution supports only the allowlisted `projectName` and `templateId` tokens. Unknown tokens fail generation; no expression evaluation is performed. +8. Files containing NUL bytes are treated as binary and copied byte-for-byte without substitution. +9. The completed staging directory is promoted to the final destination only after all template files render successfully. ## Failure and cleanup behavior diff --git a/docs/reference/troubleshooting.md b/docs/reference/troubleshooting.md index 305839a4..5690539a 100644 --- a/docs/reference/troubleshooting.md +++ b/docs/reference/troubleshooting.md @@ -123,7 +123,7 @@ A supported test project must have either: Node.js projects are run through `npm run test`; Cargo projects are run through `cargo test`. -A failing project test is preserved as a subprocess failure instead of being converted to success. +A failing project test is preserved as a subprocess failure instead of being converted to success. If npm or its launcher is missing or cannot be executed, the error identifies that prerequisite and references the supported `Node.js >=22.13.0 <25` and `npm >=10.9.0` ranges; it does not include environment values. Install a supported runtime and rerun `stellarforge doctor` before retrying. See the [`test` command reference](commands.md#stellarforge-test). diff --git a/src/commands/test.ts b/src/commands/test.ts index 324e6905..6bd1761a 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -1,11 +1,11 @@ import { Command } from 'commander'; -import { - superviseDevProcesses, - type DevOrchestratorOptions, -} from '../dev/orchestrator.js'; +import type { DevOrchestratorOptions } from '../dev/orchestrator.js'; import type { DevProcessSpec } from '../dev/project.js'; import { TerminalOutput } from '../output/terminal.js'; -import { resolveTestProcessPlan } from '../testing/project.js'; +import { + resolveTestProcessPlan, + superviseTestProcesses, +} from '../testing/project.js'; export interface TestCommandOptions extends DevOrchestratorOptions { readonly cwd?: () => string; @@ -24,6 +24,6 @@ export function createTestCommand(options: TestCommandOptions = {}): Command { output.info( `Running ${plan.length} project test workflow${plan.length === 1 ? '' : 's'}.`, ); - await superviseDevProcesses(plan, { ...options, output }); + await superviseTestProcesses(plan, { ...options, output }); }); } diff --git a/src/generator/template-generation.ts b/src/generator/template-generation.ts index 12f2bb7f..2d298d58 100644 --- a/src/generator/template-generation.ts +++ b/src/generator/template-generation.ts @@ -1,4 +1,5 @@ import { + chmodSync, existsSync, lstatSync, mkdirSync, @@ -13,6 +14,12 @@ import { } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { ValidationCliError } from '../errors/errors.js'; +import { + collectTemplateSourceTree, + GENERATED_DIRECTORY_MODE, + resolveGeneratedFileMode, + type TemplateSourceTree, +} from './template-sources.js'; import type { GenerationContext, ProjectGenerationPreview, @@ -33,6 +40,13 @@ export const GENERATED_MARKER_FILENAME = '.stellarforge.json'; /** Package identifier recorded in the generated provenance marker. */ export const GENERATOR_PACKAGE_NAME = '@diginodes/stellarforge-cli'; +interface RenderedTemplateFile { + readonly relativePath: string; + readonly content: Buffer | string; + readonly substitutions: readonly string[]; + readonly mode: number; +} + function isWithin(root: string, candidate: string): boolean { const pathFromRoot = relative(root, candidate); @@ -44,18 +58,6 @@ function isWithin(root: string, candidate: string): boolean { ); } -function assertSafeEntryName(name: string): void { - if ( - name.length === 0 || - name === '.' || - name === '..' || - name.includes('/') || - name.includes('\\') - ) { - throw new ValidationCliError('Template contains an unsafe file path.'); - } -} - function renderText( input: string, variables: Readonly>, @@ -81,74 +83,58 @@ function isBinary(content: Buffer): boolean { return content.includes(0); } -function visitTemplateTree( - templateRoot: string, - relativeDirectory: string, +function renderTemplateFiles( + tree: TemplateSourceTree, variables: Readonly>, - visitFile: ( - relativePath: string, - content: Buffer | string, - substitutions: readonly string[], - ) => void, - visitDirectory: (relativePath: string) => void, -): void { - const sourceDirectory = resolve(templateRoot, relativeDirectory); - const entries = readdirSync(sourceDirectory, { withFileTypes: true }).sort( - (a, b) => { - if (a.name < b.name) return -1; - if (a.name > b.name) return 1; - return 0; - }, - ); - - for (const entry of entries) { - assertSafeEntryName(entry.name); - - const relativePath = join(relativeDirectory, entry.name); - const sourcePath = resolve(templateRoot, relativePath); - - if (!isWithin(templateRoot, sourcePath)) { - throw new ValidationCliError( - 'Template file path escapes the trusted project root.', - ); - } - - const sourceStat = lstatSync(sourcePath); - - if (sourceStat.isSymbolicLink()) { - throw new ValidationCliError( - 'Template symbolic links are not supported.', - ); - } +): readonly RenderedTemplateFile[] { + return tree.entries + .filter((entry) => entry.type === 'file') + .map((entry) => { + const content = readFileSync(join(tree.root, entry.relativePath)); + + if (isBinary(content)) { + return { + relativePath: entry.relativePath, + content, + substitutions: [], + mode: entry.mode, + }; + } - if (sourceStat.isDirectory()) { - visitDirectory(relativePath); - visitTemplateTree( - templateRoot, - relativePath, - variables, - visitFile, - visitDirectory, - ); - continue; - } + const rendered = renderText(content.toString('utf8'), variables); + return { + relativePath: entry.relativePath, + content: rendered.content, + substitutions: rendered.substitutions, + mode: entry.mode, + }; + }); +} - if (!sourceStat.isFile()) { - throw new ValidationCliError( - 'Template contains an unsupported filesystem entry.', - ); - } +function resolveStagingPath(stagingRoot: string, relativePath: string): string { + const destinationPath = resolve(stagingRoot, relativePath); - const content = readFileSync(sourcePath); + if (!isWithin(stagingRoot, destinationPath)) { + throw new ValidationCliError( + 'Template file path escapes the trusted project root.', + ); + } - if (isBinary(content)) { - visitFile(relativePath, content, []); - continue; - } + return destinationPath; +} - const rendered = renderText(content.toString('utf8'), variables); - visitFile(relativePath, rendered.content, rendered.substitutions); +function writeRenderedFile( + destinationPath: string, + file: RenderedTemplateFile, +): void { + if (process.platform === 'win32') { + writeFileSync(destinationPath, file.content); + return; } + + const mode = resolveGeneratedFileMode(file.mode); + writeFileSync(destinationPath, file.content, { mode }); + chmodSync(destinationPath, mode); } function assertDestinationContainment(root: string, destination: string): void { @@ -214,16 +200,7 @@ export function generateProjectFromTemplate( const destinationParent = dirname(destination); const root = resolve(context.input.cwd); - if (!existsSync(templateRoot) || !lstatSync(templateRoot).isDirectory()) { - throw new ValidationCliError('Selected template source is unavailable.'); - } - - if (lstatSync(templateRoot).isSymbolicLink()) { - throw new ValidationCliError( - 'Template source must not be a symbolic link.', - ); - } - + const tree = collectTemplateSourceTree(templateRoot); assertDestinationContainment(root, destination); const destinationExisted = existsSync(destination); @@ -252,21 +229,13 @@ export function generateProjectFromTemplate( projectName: context.input.projectName, templateId: context.template.templateId, }; + const renderedFiles = renderTemplateFiles(tree, variables); if (options.dryRun) { - const files: ProjectGenerationPreviewFile[] = []; - visitTemplateTree( - templateRoot, - '.', - variables, - (relativePath, _content, substitutions) => { - files.push({ - path: relativePath.split(sep).join('/'), - substitutions, - }); - }, - () => undefined, - ); + const files: ProjectGenerationPreviewFile[] = renderedFiles.map((file) => ({ + path: file.relativePath.split(sep).join('/'), + substitutions: file.substitutions, + })); return { dryRun: true, @@ -283,36 +252,35 @@ export function generateProjectFromTemplate( let removedExistingDestination = false; try { - visitTemplateTree( - templateRoot, - '.', - variables, - (relativePath, content) => { - const destinationPath = resolve(stagingRoot, relativePath); - if (!isWithin(stagingRoot, destinationPath)) { - throw new ValidationCliError( - 'Template file path escapes the trusted project root.', - ); - } + for (const entry of tree.entries) { + if (entry.type !== 'directory') continue; - mkdirSync(dirname(destinationPath), { recursive: true }); - writeFileSync(destinationPath, content); - }, - (relativePath) => { - const destinationPath = resolve(stagingRoot, relativePath); - if (!isWithin(stagingRoot, destinationPath)) { - throw new ValidationCliError( - 'Template file path escapes the trusted project root.', - ); - } + const destinationPath = resolveStagingPath( + stagingRoot, + entry.relativePath, + ); + mkdirSync(destinationPath, { + recursive: true, + mode: GENERATED_DIRECTORY_MODE, + }); + } - mkdirSync(destinationPath, { recursive: false }); - }, - ); + for (const file of renderedFiles) { + const destinationPath = resolveStagingPath( + stagingRoot, + file.relativePath, + ); + + mkdirSync(dirname(destinationPath), { + recursive: true, + mode: GENERATED_DIRECTORY_MODE, + }); + writeRenderedFile(destinationPath, file); + } // Re-validate immediately before the mutating write phase. The checks // above can be invalidated by a concurrent destination replacement while - // copyTemplateTree was still running (it only writes into the unrelated + // staging was still running (it only writes into the unrelated // staging directory, never into `destination`), so this closes the // time-of-check/time-of-use gap rather than relying on the earlier check. assertDestinationContainment(root, destination); diff --git a/src/generator/template-sources.ts b/src/generator/template-sources.ts index 4d32cc63..6f47e1fa 100644 --- a/src/generator/template-sources.ts +++ b/src/generator/template-sources.ts @@ -1,3 +1,5 @@ +import { lstatSync, readdirSync, realpathSync } from 'node:fs'; +import { isAbsolute, join, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { ValidationCliError } from '../errors/errors.js'; import { TEMPLATE_IDS, type TemplateId } from './template-registry.js'; @@ -8,6 +10,23 @@ const BUNDLED_TEMPLATE_DIRECTORIES: Record = string >; +export const GENERATED_FILE_MODE = 0o644; +export const GENERATED_EXECUTABLE_FILE_MODE = 0o755; +export const GENERATED_DIRECTORY_MODE = 0o755; + +const EXECUTABLE_BITS = 0o111; + +export interface TemplateSourceEntry { + readonly relativePath: string; + readonly type: 'file' | 'directory'; + readonly mode: number; +} + +export interface TemplateSourceTree { + readonly root: string; + readonly entries: readonly TemplateSourceEntry[]; +} + export function resolveBundledTemplateRoot(templateId: string): string { const directory = BUNDLED_TEMPLATE_DIRECTORIES[templateId as TemplateId]; @@ -22,3 +41,146 @@ export function resolveBundledTemplateRoot(templateId: string): string { new URL(`../../templates/${directory}/`, import.meta.url), ); } + +function isWithin(root: string, candidate: string): boolean { + const pathFromRoot = relative(root, candidate); + + return ( + pathFromRoot.length > 0 && + pathFromRoot !== '..' && + !pathFromRoot.startsWith(`..${sep}`) && + !isAbsolute(pathFromRoot) + ); +} + +function assertSafeEntryName(name: string): void { + if ( + name.length === 0 || + name === '.' || + name === '..' || + name.includes('/') || + name.includes('\\') + ) { + throw new ValidationCliError('Template contains an unsafe file path.'); + } +} + +function portablePathKey(relativePath: string): string { + return relativePath.split('\\').join('/').normalize('NFD').toLowerCase(); +} + +export function assertPortableTemplatePaths( + relativePaths: readonly string[], +): void { + const seen = new Map(); + + for (const relativePath of [...new Set(relativePaths)].sort()) { + const key = portablePathKey(relativePath); + const previous = seen.get(key); + + if (previous !== undefined && previous !== relativePath) { + throw new ValidationCliError( + `Template contains colliding paths '${previous}' and '${relativePath}'.`, + ); + } + + seen.set(key, relativePath); + } +} + +export function resolveGeneratedFileMode(sourceMode: number): number { + return (sourceMode & EXECUTABLE_BITS) === 0 + ? GENERATED_FILE_MODE + : GENERATED_EXECUTABLE_FILE_MODE; +} + +function collectEntries( + root: string, + relativeDirectory: string, + entries: TemplateSourceEntry[], +): void { + const sourceDirectory = resolve(root, relativeDirectory); + const dirents = readdirSync(sourceDirectory, { withFileTypes: true }).sort( + (a, b) => { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + return 0; + }, + ); + + for (const dirent of dirents) { + assertSafeEntryName(dirent.name); + + const relativePath = join(relativeDirectory, dirent.name); + const sourcePath = resolve(root, relativePath); + + if (!isWithin(root, sourcePath)) { + throw new ValidationCliError( + 'Template file path escapes the trusted project root.', + ); + } + + const stat = lstatSync(sourcePath); + + if (stat.isSymbolicLink() || dirent.isSymbolicLink()) { + throw new ValidationCliError( + 'Template symbolic links are not supported.', + ); + } + + const realSourcePath = realpathSync(sourcePath); + if (!isWithin(root, realSourcePath)) { + throw new ValidationCliError( + 'Template file path escapes the trusted project root.', + ); + } + + if (stat.isDirectory() && dirent.isDirectory()) { + entries.push({ + relativePath, + type: 'directory', + mode: stat.mode, + }); + collectEntries(root, relativePath, entries); + continue; + } + + if (!stat.isFile() || !dirent.isFile()) { + throw new ValidationCliError( + 'Template contains an unsupported filesystem entry.', + ); + } + + entries.push({ + relativePath, + type: 'file', + mode: stat.mode, + }); + } +} + +export function collectTemplateSourceTree(templateRoot: string): TemplateSourceTree { + const root = resolve(templateRoot); + const rootStat = lstatSync(root, { throwIfNoEntry: false }); + + if (rootStat === undefined) { + throw new ValidationCliError('Selected template source is unavailable.'); + } + + if (rootStat.isSymbolicLink()) { + throw new ValidationCliError( + 'Template source must not be a symbolic link.', + ); + } + + if (!rootStat.isDirectory()) { + throw new ValidationCliError('Selected template source is unavailable.'); + } + + const realRoot = realpathSync(root); + const entries: TemplateSourceEntry[] = []; + collectEntries(realRoot, '.', entries); + assertPortableTemplatePaths(entries.map((entry) => entry.relativePath)); + + return { root: realRoot, entries }; +} diff --git a/src/process/npm.ts b/src/process/npm.ts index d730e96c..8ae61a47 100644 --- a/src/process/npm.ts +++ b/src/process/npm.ts @@ -3,6 +3,11 @@ export interface NpmInvocation { readonly args: readonly string[]; } +export type NpmInvocationFailure = 'executable-not-found' | 'permission-denied'; + +const SUPPORTED_RUNTIME_REMEDIATION = + 'Install a supported Node.js runtime (>=22.13.0 <25) and npm (>=10.9.0), then make sure npm is available on PATH.'; + export function createNpmInvocation(args: readonly string[]): NpmInvocation { if (process.platform === 'win32') { return { @@ -16,3 +21,63 @@ export function createNpmInvocation(args: readonly string[]): NpmInvocation { args: [...args], }; } + +export function isNpmInvocation(spec: NpmInvocation): boolean { + const commandIsNpm = + spec.command === 'npm' || + /(?:^|[\\/])npm(?:\.cmd|\.exe)?$/iu.test(spec.command); + const usesWindowsLauncher = + spec.command === 'cmd.exe' && + spec.args[0] === '/d' && + spec.args[1] === '/s' && + spec.args[2] === '/c' && + spec.args[3] === 'npm'; + + return commandIsNpm || usesWindowsLauncher; +} + +function hasCode(error: Error, code: string): boolean { + return ( + (error as NodeJS.ErrnoException).code === code || + new RegExp(`\\b${code}\\b`).test(error.message) + ); +} + +export function classifyNpmInvocationError( + error: unknown, +): NpmInvocationFailure | undefined { + return classifyNpmInvocationErrorWithDepth(error, 0); +} + +function classifyNpmInvocationErrorWithDepth( + error: unknown, + depth: number, +): NpmInvocationFailure | undefined { + if (!(error instanceof Error) || depth > 4) { + return undefined; + } + + if (hasCode(error, 'ENOENT')) { + return 'executable-not-found'; + } + + if (hasCode(error, 'EACCES') || hasCode(error, 'EPERM')) { + return 'permission-denied'; + } + + if (error.cause instanceof Error) { + return classifyNpmInvocationErrorWithDepth(error.cause, depth + 1); + } + + return undefined; +} + +export function npmInvocationRemediation( + failure: NpmInvocationFailure, +): string { + if (failure === 'executable-not-found') { + return `Unable to find npm or its supported launcher. ${SUPPORTED_RUNTIME_REMEDIATION}`; + } + + return `npm or its supported launcher could not be executed. ${SUPPORTED_RUNTIME_REMEDIATION}`; +} diff --git a/src/testing/project.ts b/src/testing/project.ts index 5c61722c..e18b9362 100644 --- a/src/testing/project.ts +++ b/src/testing/project.ts @@ -1,8 +1,17 @@ import { existsSync, readFileSync } from 'node:fs'; import { resolve } from 'node:path'; +import { + superviseDevProcesses, + type DevOrchestratorOptions, +} from '../dev/orchestrator.js'; import type { DevProcessSpec } from '../dev/project.js'; -import { ValidationCliError } from '../errors/errors.js'; -import { createNpmInvocation } from '../process/npm.js'; +import { SubprocessCliError, ValidationCliError } from '../errors/errors.js'; +import { + classifyNpmInvocationError, + createNpmInvocation, + isNpmInvocation, + npmInvocationRemediation, +} from '../process/npm.js'; interface ProjectPackage { readonly name?: unknown; @@ -95,3 +104,28 @@ export function resolveTestProcessPlan(cwd: string): readonly DevProcessSpec[] { 'No supported StellarForge test workflow was found. Expected a package.json test script or a Cargo.toml workspace.', ); } + +export async function superviseTestProcesses( + specs: readonly DevProcessSpec[], + options: DevOrchestratorOptions = {}, +): Promise { + const usesNpm = specs.some(isNpmInvocation); + + try { + await superviseDevProcesses(specs, options); + } catch (error) { + if (!usesNpm || !(error instanceof SubprocessCliError)) { + throw error; + } + + const failure = classifyNpmInvocationError(error.cause); + + if (failure === undefined) { + throw error; + } + + throw new SubprocessCliError(npmInvocationRemediation(failure), { + cause: error, + }); + } +} diff --git a/tests/generator-file-permissions.test.ts b/tests/generator-file-permissions.test.ts new file mode 100644 index 00000000..b964eed5 --- /dev/null +++ b/tests/generator-file-permissions.test.ts @@ -0,0 +1,112 @@ +import { + chmodSync, + mkdirSync, + readFileSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { generateProjectFromTemplate } from '../src/generator/template-generation.js'; +import type { GenerationContext } from '../src/generator/types.js'; +import { withTempDirectory } from './helpers/index.js'; + +function context(root: string): GenerationContext { + return { + input: { projectName: 'demo-app', cwd: root, templateId: 'basic-app' }, + destination: { + projectName: 'demo-app', + destination: join(root, 'demo-app'), + }, + template: { templateId: 'basic-app' }, + }; +} + +function createTemplate(root: string): { + readonly templateRoot: string; + readonly executable: string; + readonly regular: string; +} { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + const executable = join(templateRoot, 'run.sh'); + const regular = join(templateRoot, 'README.md'); + + writeFileSync(executable, '#!/bin/sh\necho ok\n'); + writeFileSync(regular, '# {{projectName}}\n'); + + return { templateRoot, executable, regular }; +} + +describe('generated-file permission policy (SW-130)', () => { + it.skipIf(process.platform === 'win32')( + 'preserves executable assets and constrains regular file modes on POSIX', + () => + withTempDirectory((root) => { + const { templateRoot, executable, regular } = createTemplate(root); + chmodSync(executable, 0o755); + chmodSync(regular, 0o666); + + generateProjectFromTemplate(context(root), { templateRoot }); + + const generatedExecutable = join(root, 'demo-app', 'run.sh'); + const generatedRegular = join(root, 'demo-app', 'README.md'); + + expect(statSync(generatedExecutable).mode & 0o777).toBe(0o755); + expect(statSync(generatedRegular).mode & 0o777).toBe(0o644); + expect(statSync(generatedRegular).mode & 0o022).toBe(0); + }), + ); + + it.skipIf(process.platform === 'win32')( + 'does not copy privileged or group/world write bits from source metadata', + () => + withTempDirectory((root) => { + const { templateRoot, executable } = createTemplate(root); + chmodSync(executable, 0o4777); + + generateProjectFromTemplate(context(root), { templateRoot }); + + expect( + statSync(join(root, 'demo-app', 'run.sh')).mode & 0o7777, + ).toBe(0o755); + }), + ); + + it('keeps generated npm project metadata usable after installation', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + writeFileSync( + join(templateRoot, 'package.json'), + JSON.stringify({ + name: '{{projectName}}', + private: true, + scripts: { check: 'node --check src/index.js', test: 'node --test' }, + }), + ); + + generateProjectFromTemplate(context(root), { templateRoot }); + + const generatedPackage = JSON.parse( + readFileSync(join(root, 'demo-app', 'package.json'), 'utf8'), + ) as { + readonly name?: unknown; + readonly scripts?: Record; + }; + expect(generatedPackage.name).toBe('demo-app'); + expect(generatedPackage.scripts?.check).toBe('node --check src/index.js'); + expect(generatedPackage.scripts?.test).toBe('node --test'); + })); + + it('generates successfully on Windows without POSIX chmod support', () => + withTempDirectory((root) => { + const { templateRoot } = createTemplate(root); + + generateProjectFromTemplate(context(root), { templateRoot }); + + expect(readFileSync(join(root, 'demo-app', 'run.sh'), 'utf8')).toContain( + 'echo ok', + ); + })); +}); diff --git a/tests/generator-path-collisions.test.ts b/tests/generator-path-collisions.test.ts new file mode 100644 index 00000000..b0299fbc --- /dev/null +++ b/tests/generator-path-collisions.test.ts @@ -0,0 +1,128 @@ +import { + existsSync, + mkdirSync, + readFileSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { assertPortableTemplatePaths } from '../src/generator/template-sources.js'; +import { generateProjectFromTemplate } from '../src/generator/template-generation.js'; +import type { GenerationContext } from '../src/generator/types.js'; +import { withTempDirectory } from './helpers/index.js'; + +const ORIGINAL_PLATFORM = process.platform; + +function onPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { + value: platform, + configurable: true, + }); +} + +afterEach(() => { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); +}); + +function context(root: string): GenerationContext { + return { + input: { projectName: 'demo-app', cwd: root, templateId: 'basic-app' }, + destination: { + projectName: 'demo-app', + destination: join(root, 'demo-app'), + }, + template: { templateId: 'basic-app' }, + }; +} + +function bothPathsAreDistinct( + first: string, + second: string, + firstContent: string, +): boolean { + return ( + existsSync(first) && + existsSync(second) && + readFileSync(first, 'utf8') === firstContent + ); +} + +describe('portable template path policy (SW-129)', () => { + it('rejects case-folding collisions before creating any generated file', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + const first = join(templateRoot, 'README.md'); + const second = join(templateRoot, 'readme.md'); + writeFileSync(first, 'first'); + writeFileSync(second, 'second'); + + if (!bothPathsAreDistinct(first, second, 'first')) return; + + expect(() => + generateProjectFromTemplate(context(root), { templateRoot }), + ).toThrow(/colliding paths 'README\.md' and 'readme\.md'/); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + })); + + it('rejects Unicode normalization collisions before creating any generated file', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + const first = join(templateRoot, 'caf\u00E9.txt'); + const second = join(templateRoot, 'cafe\u0301.txt'); + writeFileSync(first, 'first'); + writeFileSync(second, 'second'); + + if (!bothPathsAreDistinct(first, second, 'first')) return; + + expect(() => + generateProjectFromTemplate(context(root), { templateRoot }), + ).toThrow(/colliding paths/); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + })); + + it('reports identical collision guidance on Linux, macOS, and Windows', () => { + const paths = ['src/Caf\u00E9.txt', 'src/cafe\u0301.txt']; + let expectedMessage: string | undefined; + + for (const platform of ['linux', 'darwin', 'win32'] as const) { + onPlatform(platform); + + let message: string | undefined; + try { + assertPortableTemplatePaths(paths); + } catch (error) { + message = error instanceof Error ? error.message : undefined; + } + + expect(message).toBeDefined(); + if (expectedMessage === undefined) { + expectedMessage = message; + } else { + expect(message).toBe(expectedMessage); + } + } + }); + + it('keeps valid non-colliding case-distinct paths supported', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(join(templateRoot, 'src'), { recursive: true }); + writeFileSync(join(templateRoot, 'package.json'), '{"name":"demo"}'); + writeFileSync(join(templateRoot, 'src', 'Alpha.ts'), 'alpha'); + writeFileSync(join(templateRoot, 'src', 'beta.ts'), 'beta'); + + generateProjectFromTemplate(context(root), { templateRoot }); + + expect( + readFileSync(join(root, 'demo-app', 'src', 'Alpha.ts'), 'utf8'), + ).toBe('alpha'); + expect( + readFileSync(join(root, 'demo-app', 'src', 'beta.ts'), 'utf8'), + ).toBe('beta'); + })); +}); diff --git a/tests/generator-symlink-ancestor.test.ts b/tests/generator-symlink-ancestor.test.ts index 66096911..2a61ba7b 100644 --- a/tests/generator-symlink-ancestor.test.ts +++ b/tests/generator-symlink-ancestor.test.ts @@ -41,6 +41,23 @@ function canCreateSymlinks(): boolean { const symlinksSupported = canCreateSymlinks(); +function canCreateFileSymlinks(): boolean { + const fixture = createTempDirectoryFixture(); + try { + symlinkSync( + join(fixture.path, 'probe-target'), + join(fixture.path, 'probe-link'), + ); + return true; + } catch { + return false; + } finally { + fixture.cleanup(); + } +} + +const fileSymlinksSupported = canCreateFileSymlinks(); + function createMinimalTemplate(root: string): string { const templateRoot = join(root, 'template'); mkdirSync(join(templateRoot, 'src'), { recursive: true }); @@ -321,3 +338,80 @@ describe('generator symlink-ancestor containment (SW-032)', () => { }), ); }); + +describe('bundled template source symlink policy (SW-131)', () => { + it.skipIf(!symlinksSupported && !fileSymlinksSupported)( + 'rejects a dangling symlink entry before writing the generated project', + () => + withTempDirectory((root) => { + const templateRoot = createMinimalTemplate(root); + + if (fileSymlinksSupported) { + symlinkSync( + join(templateRoot, 'missing-target.txt'), + join(templateRoot, 'dangling.txt'), + ); + } else { + symlinkSync( + join(root, 'missing-target-dir'), + join(templateRoot, 'dangling-dir'), + 'junction', + ); + } + + expect(() => + generateProjectFromTemplate( + createContext(root, join(root, 'demo-app')), + { templateRoot }, + ), + ).toThrow('Template symbolic links are not supported.'); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + expect(stagingLeftovers(root)).toEqual([]); + }), + ); + + it.skipIf(!symlinksSupported)( + 'rejects a symlink whose resolved target escapes the template root', + () => + withTempDirectory((root) => { + const templateRoot = createMinimalTemplate(root); + const outside = createTempDirectoryFixture(); + try { + const outsideFile = join(outside.path, 'secret.txt'); + writeFileSync(outsideFile, 'outside-template-content'); + symlinkSync(outsideFile, join(templateRoot, 'escape.txt')); + + expect(() => + generateProjectFromTemplate( + createContext(root, join(root, 'demo-app')), + { templateRoot }, + ), + ).toThrow(ValidationCliError); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + expect(stagingLeftovers(root)).toEqual([]); + expect(stagingLeftovers(outside.path)).toEqual([]); + } finally { + outside.cleanup(); + } + }), + ); + + it('continues to generate regular files and directories', () => + withTempDirectory((root) => { + const templateRoot = createMinimalTemplate(root); + const destination = join(root, 'demo-app'); + + const result = generateProjectFromTemplate( + createContext(root, destination), + { templateRoot }, + ); + + expect(result.destination).toBe(destination); + expect(readFileSync(join(destination, 'package.json'), 'utf8')).toContain( + '"name":"demo-app"', + ); + expect( + readFileSync(join(destination, 'src', 'index.ts'), 'utf8'), + ).toContain('"demo-app"'); + })); +}); diff --git a/tests/test-missing-npm-remediation.test.ts b/tests/test-missing-npm-remediation.test.ts new file mode 100644 index 00000000..30c7d152 --- /dev/null +++ b/tests/test-missing-npm-remediation.test.ts @@ -0,0 +1,156 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { createTestCommand } from '../src/commands/test.js'; +import type { DevProcessSpec } from '../src/dev/project.js'; +import { SubprocessCliError } from '../src/errors/errors.js'; +import { createNpmInvocation } from '../src/process/npm.js'; +import { + createCapturedTerminalOutput, + FakeChildProcess, +} from './helpers/index.js'; + +const ORIGINAL_PLATFORM = process.platform; + +function onPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { + value: platform, + configurable: true, + }); +} + +afterEach(() => { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); +}); + +function npmPlan(label = 'demo:test'): readonly DevProcessSpec[] { + const npm = createNpmInvocation(['run', 'test']); + return [{ label, command: npm.command, args: npm.args, cwd: '/workspace' }]; +} + +function errnoError(code: 'ENOENT' | 'EACCES'): Error { + const error = new Error( + `spawn npm ${code} PATH=/secret-runtime-path SECRET_TOKEN=do-not-echo`, + ) as NodeJS.ErrnoException; + error.code = code; + return error; +} + +async function rejectionOf(running: Promise): Promise { + return running.then( + () => undefined, + (reason: unknown) => reason, + ); +} + +describe('test workflow package-manager remediation (SW-157)', () => { + it('classifies executable-not-found separately from a failing test script', async () => { + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => npmPlan(), + spawnProcess: () => { + throw errnoError('ENOENT'); + }, + }); + + const error = await rejectionOf(command.parseAsync(['node', 'test'])); + + expect(error).toBeInstanceOf(SubprocessCliError); + const message = (error as SubprocessCliError).userMessage; + expect(message).toContain('Unable to find npm or its supported launcher'); + expect(message).toContain('Node.js >=22.13.0 <25'); + expect(message).toContain('npm >=10.9.0'); + expect(message).not.toContain('exited unexpectedly'); + expect(message).not.toContain('SECRET_TOKEN'); + expect(message).not.toContain('/secret-runtime-path'); + }); + + it('reports permission-denied with the same supported runtime guidance', async () => { + const child = new FakeChildProcess(); + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => npmPlan(), + spawnProcess: () => child, + }); + + const running = command.parseAsync(['node', 'test']); + const childFailure = child.fail(errnoError('EACCES')); + const error = await rejectionOf(running); + await childFailure; + + expect(error).toBeInstanceOf(SubprocessCliError); + const message = (error as SubprocessCliError).userMessage; + expect(message).toContain('could not be executed'); + expect(message).toContain('Node.js >=22.13.0 <25'); + expect(message).toContain('npm >=10.9.0'); + expect(message).not.toContain('SECRET_TOKEN'); + }); + + it('preserves an ordinary test-script failure without missing-npm guidance', async () => { + const child = new FakeChildProcess(); + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => npmPlan(), + spawnProcess: () => child, + }); + + const running = command.parseAsync(['node', 'test']); + const childResult = child.finish(9); + const error = await rejectionOf(running); + await childResult; + + expect(error).toBeInstanceOf(SubprocessCliError); + const message = (error as SubprocessCliError).userMessage; + expect(message).toContain('with code 9'); + expect(message).not.toContain('supported Node.js runtime'); + }); + + it('keeps the Windows npm launcher and reports its startup failure', async () => { + onPlatform('win32'); + let spawned = false; + const plan = npmPlan(); + + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => plan, + spawnProcess: (spec) => { + spawned = true; + expect(spec.command).toBe('cmd.exe'); + expect(spec.args.slice(0, 4)).toEqual(['/d', '/s', '/c', 'npm']); + throw errnoError('ENOENT'); + }, + }); + + const error = await rejectionOf(command.parseAsync(['node', 'test'])); + + expect(spawned).toBe(true); + expect((error as SubprocessCliError).userMessage).toContain( + 'Unable to find npm or its supported launcher', + ); + }); + + it('does not echo the supplied process environment', async () => { + const captured = createCapturedTerminalOutput(); + const command = createTestCommand({ + cwd: () => '/workspace', + output: captured.output, + environment: { + PATH: '/usr/bin', + SECRET_TOKEN: 'super-secret-value', + }, + resolvePlan: () => npmPlan(), + spawnProcess: () => { + throw errnoError('ENOENT'); + }, + }); + + const error = await rejectionOf(command.parseAsync(['node', 'test'])); + + expect((error as SubprocessCliError).userMessage).not.toContain( + 'super-secret-value', + ); + expect(captured.stdoutText()).not.toContain('super-secret-value'); + expect(captured.stderrText()).not.toContain('super-secret-value'); + }); +});