diff --git a/dist-gha/index.js b/dist-gha/index.js index 736db57..6e6a262 100644 --- a/dist-gha/index.js +++ b/dist-gha/index.js @@ -69279,6 +69279,7 @@ __nccwpck_require__.d(oas_schema_namespaceObject, { var ordering_namespaceObject = {}; __nccwpck_require__.r(ordering_namespaceObject); __nccwpck_require__.d(ordering_namespaceObject, { + CONTENT_DIRS: () => (ordering_CONTENT_DIRS), name: () => (ordering_name), validateAll: () => (ordering_validateAll) }); @@ -73906,6 +73907,8 @@ function frontmatter_validate({ content, filePath, relativePath, fix }) { } // Step 5: Apply fixes — rename unknown (non-typo) properties to x- prefixed. + // Symlinks are refused in runValidators before this runs, so the write stays + // inside the repository. if (fix && filePath) { const typoKeys = new Set([...consumed].map(r => r._key)); const keysToFix = unknownKeys.filter(key => !typoKeys.has(key) && !suggestedTypos.has(key)); @@ -74064,7 +74067,9 @@ function nesting_validateAll(files) { /** * A path that would leave `baseDir`, including by following a symlink. `target` is the refused - * path (the symlink itself when that is what was hit). + * path under `baseDir` (the symlink itself when that is what was hit). It is not that path's + * realpath: `baseDir` may sit behind a symlink such as `/var` → `/private/var`, and callers + * use `path.relative(baseDir, target)`. */ class PathEscapeError extends Error { constructor(target, reason) { @@ -74106,12 +74111,17 @@ function makeContainment(baseDir, { label = 'reference directory' } = {}) { } let cursor = baseReal; + const walked = []; for (const segment of rel.split(external_node_path_namespaceObject.sep)) { if (segment === '' || segment === '.' || segment === '..') { throw new PathEscapeError(resolved, `path escapes the ${label}`); } + walked.push(segment); cursor = external_node_path_namespaceObject.join(cursor, segment); + // `cursor` follows the realpath of the base. The error names the same segment under the + // base the caller passed, so path.relative(baseDir, target) stays inside it. + const lexical = external_node_path_namespaceObject.join(baseResolved, ...walked); let st; try { @@ -74131,7 +74141,7 @@ function makeContainment(baseDir, { label = 'reference directory' } = {}) { } if (st.isSymbolicLink()) { - throw new PathEscapeError(cursor, `symbolic links inside the ${label} are not followed`); + throw new PathEscapeError(lexical, `symbolic links inside the ${label} are not followed`); } } @@ -92115,6 +92125,8 @@ async function oas_schema_validateAll(files, gitRoot) { + + const ordering_name = 'ordering'; // Top-level content directories that use _order.yaml. @@ -92159,7 +92171,7 @@ function isIndex(name) { * slug set (child pages + child folders) and its _order.yaml entries (or null * when absent), so the caller can diff the two in a single pass. */ -function collectDirs(gitRoot, topDir) { +function collectDirs(gitRoot, topDir, assertContained) { const base = external_node_path_namespaceObject.join(gitRoot, topDir); if (!external_node_fs_namespaceObject.existsSync(base)) return []; @@ -92169,19 +92181,39 @@ function collectDirs(gitRoot, topDir) { const cur = stack.pop(); const onDisk = new Set(); let orderEntries = null; + let refused = null; + + // `readdir` follows a symlink directory. Refuse it before listing, so a + // linked `docs/` cannot supply slugs or an order file from outside the repo. + let listing; + try { + assertContained(cur); + listing = external_node_fs_namespaceObject.readdirSync(cur, { withFileTypes: true }); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + dirs.push({ dir: cur, onDisk, orderEntries, refused: err }); + continue; + } - for (const entry of external_node_fs_namespaceObject.readdirSync(cur, { withFileTypes: true })) { + for (const entry of listing) { + const entryPath = external_node_path_namespaceObject.join(cur, entry.name); if (entry.isDirectory()) { onDisk.add(entry.name); - stack.push(external_node_path_namespaceObject.join(cur, entry.name)); + stack.push(entryPath); } else if (entry.name === '_order.yaml') { - orderEntries = ordering_parseOrderYaml(external_node_fs_namespaceObject.readFileSync(external_node_path_namespaceObject.join(cur, entry.name), 'utf-8')); + try { + assertContained(entryPath); + orderEntries = ordering_parseOrderYaml(external_node_fs_namespaceObject.readFileSync(entryPath, 'utf-8')); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + refused = err; + } } else if (/\.(md|mdx)$/.test(entry.name) && !isIndex(entry.name)) { onDisk.add(entry.name.replace(/\.(md|mdx)$/, '')); } } - dirs.push({ dir: cur, onDisk, orderEntries }); + dirs.push({ dir: cur, onDisk, orderEntries, refused }); } return dirs; } @@ -92193,15 +92225,27 @@ function collectDirs(gitRoot, topDir) { * - an index entry that shouldn't be listed → "Invalid entry" */ function ordering_validateAll(files, gitRoot, { fix } = {}) { + const assertContained = makeContainment(gitRoot, { label: 'repository' }); const results = []; for (const topDir of ordering_CONTENT_DIRS) { const requireOrder = REQUIRE_ORDER.has(topDir); - for (const { dir, onDisk, orderEntries } of collectDirs(gitRoot, topDir)) { + for (const { dir, onDisk, orderEntries, refused } of collectDirs(gitRoot, topDir, assertContained)) { const orderPath = external_node_path_namespaceObject.join(dir, '_order.yaml'); const relOrder = external_node_path_namespaceObject.relative(gitRoot, orderPath); + if (refused) { + results.push({ + file: external_node_path_namespaceObject.relative(gitRoot, refused.target), + rule: ordering_name, + severity: 'error', + message: refused.message, + fixable: false, + }); + continue; + } + // No _order.yaml at all: only required dirs need one. if (orderEntries === null) { if (requireOrder && onDisk.size > 0) { @@ -92262,7 +92306,8 @@ function ordering_validateAll(files, gitRoot, { fix } = {}) { if (!fix) return strip(results); - // Additions: append missing slugs to the _order.yaml. + // Additions: append missing slugs to the _order.yaml. A path only reaches + // here after collectDirs admitted it, so the write stays inside the repo. for (const r of results) { if (!r._fixAdd) continue; const { orderPath, missing } = r._fixAdd; @@ -92471,6 +92516,8 @@ function recipes_validate({ content, relativePath }) { + + const TARGET_PATTERNS = [ { dir: 'custom_blocks', ext: ['.mdx', '.md'] }, { dir: 'docs', ext: '.md' }, @@ -92487,7 +92534,17 @@ function collectFiles(gitRoot) { for (const { dir, ext } of TARGET_PATTERNS) { const dirPath = external_node_path_namespaceObject.join(gitRoot, dir); - if (!external_node_fs_namespaceObject.existsSync(dirPath)) continue; + // `readdir` follows a symlink at `dirPath`. A linked content root is not a + // directory this walk lists; `lstat` is what sees the link. ordering + // reports the roots it walks; runValidators reports every other one. + let st; + try { + st = external_node_fs_namespaceObject.lstatSync(dirPath); + } catch (err) { + if (err.code === 'ENOENT') continue; + throw err; + } + if (!st.isDirectory()) continue; const exts = Array.isArray(ext) ? ext : [ext]; const entries = external_node_fs_namespaceObject.readdirSync(dirPath, { recursive: true }); @@ -92535,12 +92592,55 @@ function loadValidators() { async function runValidators(files, gitRoot, { onFile, onBeforeCrossFile, fix, nonInteractive } = {}) { const validators = await loadValidators(); const results = []; + const assertContained = makeContainment(gitRoot, { label: 'repository' }); + // ordering refuses a linked docs/reference/recipes/custom_pages root. + // collectFiles skips every linked root, so a root ordering does not walk + // (custom_blocks) would otherwise lint as a clean repository. + const orderedRoots = new Set(ordering_CONTENT_DIRS); + for (const { dir } of TARGET_PATTERNS) { + if (orderedRoots.has(dir)) continue; + try { + assertContained(external_node_path_namespaceObject.join(gitRoot, dir)); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + results.push({ + file: dir, + rule: 'path', + severity: 'error', + message: err.message, + fixable: false, + }); + } + } + + // A fix rewrites the file it just read. Refuse a symlink here, once, before any + // validator sees the path. `pretty` does the same check at its open. + // Cross-file checks read the list again, and links does that with no guard, + // so a refused path stays out of the list they receive. + const admitted = []; // Per-file validators. for (const relativePath of files) { if (onFile) onFile(relativePath); const filePath = external_node_path_namespaceObject.join(gitRoot, relativePath); + if (fix) { + try { + assertContained(filePath); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + results.push({ + file: relativePath, + rule: 'path', + severity: 'error', + message: err.message, + fixable: false, + }); + continue; + } + } + + admitted.push(relativePath); const content = external_node_fs_namespaceObject.readFileSync(filePath, 'utf-8'); for (const validator of validators) { @@ -92560,7 +92660,7 @@ async function runValidators(files, gitRoot, { onFile, onBeforeCrossFile, fix, n if (onBeforeCrossFile) onBeforeCrossFile(); for (const validator of validators) { if (!validator.validateAll) continue; - const result = await validator.validateAll(files, gitRoot, { fix, nonInteractive }); + const result = await validator.validateAll(admitted, gitRoot, { fix, nonInteractive }); if (result) { if (Array.isArray(result)) { results.push(...result); diff --git a/src/utils/containment.js b/src/utils/containment.js index 05dd912..d28bbd9 100644 --- a/src/utils/containment.js +++ b/src/utils/containment.js @@ -3,7 +3,9 @@ import path from 'node:path'; /** * A path that would leave `baseDir`, including by following a symlink. `target` is the refused - * path (the symlink itself when that is what was hit). + * path under `baseDir` (the symlink itself when that is what was hit). It is not that path's + * realpath: `baseDir` may sit behind a symlink such as `/var` → `/private/var`, and callers + * use `path.relative(baseDir, target)`. */ export class PathEscapeError extends Error { constructor(target, reason) { @@ -45,12 +47,17 @@ export function makeContainment(baseDir, { label = 'reference directory' } = {}) } let cursor = baseReal; + const walked = []; for (const segment of rel.split(path.sep)) { if (segment === '' || segment === '.' || segment === '..') { throw new PathEscapeError(resolved, `path escapes the ${label}`); } + walked.push(segment); cursor = path.join(cursor, segment); + // `cursor` follows the realpath of the base. The error names the same segment under the + // base the caller passed, so path.relative(baseDir, target) stays inside it. + const lexical = path.join(baseResolved, ...walked); let st; try { @@ -70,7 +77,7 @@ export function makeContainment(baseDir, { label = 'reference directory' } = {}) } if (st.isSymbolicLink()) { - throw new PathEscapeError(cursor, `symbolic links inside the ${label} are not followed`); + throw new PathEscapeError(lexical, `symbolic links inside the ${label} are not followed`); } } diff --git a/src/utils/lint.js b/src/utils/lint.js index 4414022..dbbb23a 100644 --- a/src/utils/lint.js +++ b/src/utils/lint.js @@ -12,6 +12,8 @@ import * as oasSchemaValidator from '../validators/oas-schema.js'; import * as orderingValidator from '../validators/ordering.js'; import * as recipesValidator from '../validators/recipes.js'; +import { makeContainment, PathEscapeError } from './containment.js'; + const TARGET_PATTERNS = [ { dir: 'custom_blocks', ext: ['.mdx', '.md'] }, { dir: 'docs', ext: '.md' }, @@ -28,7 +30,17 @@ export function collectFiles(gitRoot) { for (const { dir, ext } of TARGET_PATTERNS) { const dirPath = path.join(gitRoot, dir); - if (!fs.existsSync(dirPath)) continue; + // `readdir` follows a symlink at `dirPath`. A linked content root is not a + // directory this walk lists; `lstat` is what sees the link. ordering + // reports the roots it walks; runValidators reports every other one. + let st; + try { + st = fs.lstatSync(dirPath); + } catch (err) { + if (err.code === 'ENOENT') continue; + throw err; + } + if (!st.isDirectory()) continue; const exts = Array.isArray(ext) ? ext : [ext]; const entries = fs.readdirSync(dirPath, { recursive: true }); @@ -76,12 +88,55 @@ function loadValidators() { export async function runValidators(files, gitRoot, { onFile, onBeforeCrossFile, fix, nonInteractive } = {}) { const validators = await loadValidators(); const results = []; + const assertContained = makeContainment(gitRoot, { label: 'repository' }); + // ordering refuses a linked docs/reference/recipes/custom_pages root. + // collectFiles skips every linked root, so a root ordering does not walk + // (custom_blocks) would otherwise lint as a clean repository. + const orderedRoots = new Set(orderingValidator.CONTENT_DIRS); + for (const { dir } of TARGET_PATTERNS) { + if (orderedRoots.has(dir)) continue; + try { + assertContained(path.join(gitRoot, dir)); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + results.push({ + file: dir, + rule: 'path', + severity: 'error', + message: err.message, + fixable: false, + }); + } + } + + // A fix rewrites the file it just read. Refuse a symlink here, once, before any + // validator sees the path. `pretty` does the same check at its open. + // Cross-file checks read the list again, and links does that with no guard, + // so a refused path stays out of the list they receive. + const admitted = []; // Per-file validators. for (const relativePath of files) { if (onFile) onFile(relativePath); const filePath = path.join(gitRoot, relativePath); + if (fix) { + try { + assertContained(filePath); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + results.push({ + file: relativePath, + rule: 'path', + severity: 'error', + message: err.message, + fixable: false, + }); + continue; + } + } + + admitted.push(relativePath); const content = fs.readFileSync(filePath, 'utf-8'); for (const validator of validators) { @@ -101,7 +156,7 @@ export async function runValidators(files, gitRoot, { onFile, onBeforeCrossFile, if (onBeforeCrossFile) onBeforeCrossFile(); for (const validator of validators) { if (!validator.validateAll) continue; - const result = await validator.validateAll(files, gitRoot, { fix, nonInteractive }); + const result = await validator.validateAll(admitted, gitRoot, { fix, nonInteractive }); if (result) { if (Array.isArray(result)) { results.push(...result); diff --git a/src/validators/frontmatter.js b/src/validators/frontmatter.js index 275583b..8f20130 100644 --- a/src/validators/frontmatter.js +++ b/src/validators/frontmatter.js @@ -214,6 +214,8 @@ export function validate({ content, filePath, relativePath, fix }) { } // Step 5: Apply fixes — rename unknown (non-typo) properties to x- prefixed. + // Symlinks are refused in runValidators before this runs, so the write stays + // inside the repository. if (fix && filePath) { const typoKeys = new Set([...consumed].map(r => r._key)); const keysToFix = unknownKeys.filter(key => !typoKeys.has(key) && !suggestedTypos.has(key)); diff --git a/src/validators/ordering.js b/src/validators/ordering.js index e2037d6..d017bdc 100644 --- a/src/validators/ordering.js +++ b/src/validators/ordering.js @@ -1,10 +1,12 @@ import fs from 'node:fs'; import path from 'node:path'; +import { makeContainment, PathEscapeError } from '../utils/containment.js'; + export const name = 'ordering'; // Top-level content directories that use _order.yaml. -const CONTENT_DIRS = ['docs', 'reference', 'recipes', 'custom_pages']; +export const CONTENT_DIRS = ['docs', 'reference', 'recipes', 'custom_pages']; // Of those, the dirs that must list every page/folder. reference ordering is // OAS-managed, so we never flag pages "missing from" a reference _order.yaml — @@ -45,7 +47,7 @@ function isIndex(name) { * slug set (child pages + child folders) and its _order.yaml entries (or null * when absent), so the caller can diff the two in a single pass. */ -function collectDirs(gitRoot, topDir) { +function collectDirs(gitRoot, topDir, assertContained) { const base = path.join(gitRoot, topDir); if (!fs.existsSync(base)) return []; @@ -55,19 +57,39 @@ function collectDirs(gitRoot, topDir) { const cur = stack.pop(); const onDisk = new Set(); let orderEntries = null; + let refused = null; + + // `readdir` follows a symlink directory. Refuse it before listing, so a + // linked `docs/` cannot supply slugs or an order file from outside the repo. + let listing; + try { + assertContained(cur); + listing = fs.readdirSync(cur, { withFileTypes: true }); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + dirs.push({ dir: cur, onDisk, orderEntries, refused: err }); + continue; + } - for (const entry of fs.readdirSync(cur, { withFileTypes: true })) { + for (const entry of listing) { + const entryPath = path.join(cur, entry.name); if (entry.isDirectory()) { onDisk.add(entry.name); - stack.push(path.join(cur, entry.name)); + stack.push(entryPath); } else if (entry.name === '_order.yaml') { - orderEntries = parseOrderYaml(fs.readFileSync(path.join(cur, entry.name), 'utf-8')); + try { + assertContained(entryPath); + orderEntries = parseOrderYaml(fs.readFileSync(entryPath, 'utf-8')); + } catch (err) { + if (!(err instanceof PathEscapeError)) throw err; + refused = err; + } } else if (/\.(md|mdx)$/.test(entry.name) && !isIndex(entry.name)) { onDisk.add(entry.name.replace(/\.(md|mdx)$/, '')); } } - dirs.push({ dir: cur, onDisk, orderEntries }); + dirs.push({ dir: cur, onDisk, orderEntries, refused }); } return dirs; } @@ -79,15 +101,27 @@ function collectDirs(gitRoot, topDir) { * - an index entry that shouldn't be listed → "Invalid entry" */ export function validateAll(files, gitRoot, { fix } = {}) { + const assertContained = makeContainment(gitRoot, { label: 'repository' }); const results = []; for (const topDir of CONTENT_DIRS) { const requireOrder = REQUIRE_ORDER.has(topDir); - for (const { dir, onDisk, orderEntries } of collectDirs(gitRoot, topDir)) { + for (const { dir, onDisk, orderEntries, refused } of collectDirs(gitRoot, topDir, assertContained)) { const orderPath = path.join(dir, '_order.yaml'); const relOrder = path.relative(gitRoot, orderPath); + if (refused) { + results.push({ + file: path.relative(gitRoot, refused.target), + rule: name, + severity: 'error', + message: refused.message, + fixable: false, + }); + continue; + } + // No _order.yaml at all: only required dirs need one. if (orderEntries === null) { if (requireOrder && onDisk.size > 0) { @@ -148,7 +182,8 @@ export function validateAll(files, gitRoot, { fix } = {}) { if (!fix) return strip(results); - // Additions: append missing slugs to the _order.yaml. + // Additions: append missing slugs to the _order.yaml. A path only reaches + // here after collectDirs admitted it, so the write stays inside the repo. for (const r of results) { if (!r._fixAdd) continue; const { orderPath, missing } = r._fixAdd; diff --git a/test/security/lint-fix-symlink.test.js b/test/security/lint-fix-symlink.test.js new file mode 100644 index 0000000..c751de9 --- /dev/null +++ b/test/security/lint-fix-symlink.test.js @@ -0,0 +1,180 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { expect, test } from 'vitest'; + +import { lint } from '../../src/commands/lint.js'; +import { makeRepo, rmRepo } from '../helpers.js'; + +const page = '---\ntitle: x\n---\nbody\n'; + +// The walk admits a directory or an order file once. These three links are the +// ways that admission can fail, and each one used to be a write to the target. +const orderEscapes = [ + { + name: 'append through a symlinked _order.yaml', + file: 'docs/_order.yaml', + arrange(root, outside) { + const original = 'keep\n'; + const victim = path.join(outside, 'outside.txt'); + fs.mkdirSync(path.join(root, 'docs')); + fs.writeFileSync(path.join(root, 'docs/a.md'), page); + fs.writeFileSync(path.join(root, 'docs/pwned.md'), page); + fs.writeFileSync(victim, original); + fs.symlinkSync(victim, path.join(root, 'docs/_order.yaml')); + return { victim, original, outsideListing: ['outside.txt'] }; + }, + }, + { + name: 'rewrite lines through a symlinked _order.yaml', + file: 'docs/_order.yaml', + hidden: ['keep', 'other'], + arrange(root, outside) { + const original = '# outside list\n- keep\n- other\n'; + const victim = path.join(outside, 'outside.txt'); + fs.mkdirSync(path.join(root, 'docs')); + fs.writeFileSync(path.join(root, 'docs/a.md'), page); + fs.writeFileSync(path.join(root, 'docs/pwned.md'), page); + fs.writeFileSync(victim, original); + fs.symlinkSync(victim, path.join(root, 'docs/_order.yaml')); + return { victim, original, outsideListing: ['outside.txt'] }; + }, + }, + { + name: 'follow a symlinked docs directory', + file: 'docs', + arrange(root, outside) { + const original = '---\ntitle: x\nfoo: 1\n---\nbody\n'; + const victim = path.join(outside, 'a.md'); + fs.writeFileSync(victim, original); + fs.writeFileSync(path.join(outside, 'pwned.md'), page); + fs.symlinkSync(outside, path.join(root, 'docs')); + return { victim, original, outsideListing: ['a.md', 'pwned.md'] }; + }, + }, +]; + +test.each(orderEscapes)('lint --fix does not $name', async ({ file, hidden, arrange }) => { + const root = makeRepo({}); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rdme-cli-outside-')); + const { victim, original, outsideListing } = arrange(root, outside); + try { + const { results } = await lint({ cwd: root, fix: true }); + const refusals = results.filter(r => r.message.includes('symbolic links')); + expect(refusals).toHaveLength(1); + const refusal = refusals[0]; + expect(refusal).toMatchObject({ file, rule: 'ordering', severity: 'error', fixable: false }); + expect(refusal.message).not.toContain('(fixed)'); + for (const word of hidden ?? []) { + expect(results.some(r => r.message.includes(word))).toBe(false); + } + expect(fs.readFileSync(victim, 'utf-8')).toBe(original); + expect(fs.readdirSync(outside).sort()).toStrictEqual(outsideListing); + } finally { + rmRepo(root); + fs.rmSync(outside, { recursive: true, force: true }); + } +}); + +test('lint --fix does not rewrite frontmatter through a symlinked page', async () => { + const body = '---\ntitle: x\nfoo: 1\n---\nbody\n'; + const root = makeRepo({}); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rdme-cli-outside-')); + fs.mkdirSync(path.join(root, 'docs')); + const victim = path.join(outside, 'page.md'); + fs.writeFileSync(victim, body); + const link = path.join(root, 'docs/x.md'); + fs.symlinkSync(victim, link); + try { + const { results } = await lint({ cwd: root, fix: true }); + const refusal = results.find(r => r.rule === 'path' && r.message.includes('symbolic links')); + expect(refusal).toMatchObject({ + file: 'docs/x.md', + severity: 'error', + fixable: false, + }); + expect(refusal.message).not.toContain('(fixed)'); + expect(fs.readFileSync(victim, 'utf-8')).toBe(body); + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + } finally { + rmRepo(root); + fs.rmSync(outside, { recursive: true, force: true }); + } +}); + +test('lint --fix reports a dangling page symlink instead of throwing', async () => { + const root = makeRepo({ + 'docs/ok.md': '---\ntitle: ok\n---\n[missing](doc:nope)\n', + 'docs/_order.yaml': '- ok\n', + }); + fs.symlinkSync(path.join(root, 'does-not-exist.md'), path.join(root, 'docs/gone.md')); + try { + const { results, hasErrors } = await lint({ cwd: root, fix: true }); + expect(hasErrors).toBe(true); + expect(results).toContainEqual( + expect.objectContaining({ + file: 'docs/gone.md', + rule: 'path', + severity: 'error', + fixable: false, + }), + ); + expect(results.some(r => r.rule === 'links' && r.file === 'docs/ok.md')).toBe(true); + } finally { + rmRepo(root); + } +}); + +test('lint reports a symlinked custom_blocks directory and does not rewrite it', async () => { + const body = '---\nname: Block\nfoo: 1\n---\nexport const Block = () => null\n\n\n'; + const root = makeRepo({}); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rdme-cli-outside-')); + const victim = path.join(outside, 'Block.mdx'); + fs.writeFileSync(victim, body); + fs.symlinkSync(outside, path.join(root, 'custom_blocks')); + try { + const { results, hasErrors } = await lint({ cwd: root, fix: true }); + expect(hasErrors).toBe(true); + const refusals = results.filter(r => r.message.includes('symbolic links')); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + file: 'custom_blocks', + rule: 'path', + severity: 'error', + fixable: false, + }); + expect(fs.readFileSync(victim, 'utf-8')).toBe(body); + } finally { + rmRepo(root); + fs.rmSync(outside, { recursive: true, force: true }); + } +}); + +test('lint does not flag a real custom_blocks directory', async () => { + const root = makeRepo({ + 'custom_blocks/myBlock.md': 'A snippet.\n', + }); + try { + const { results } = await lint({ cwd: root }); + expect(results.some(r => r.file === 'custom_blocks' && r.rule === 'path')).toBe(false); + expect(results.some(r => r.file === 'custom_blocks/myBlock.md')).toBe(true); + } finally { + rmRepo(root); + } +}); + +test('lint --fix still rewrites a real page', async () => { + const root = makeRepo({ + 'docs/x.md': '---\ntitle: x\nfoo: 1\n---\nbody\n', + 'docs/_order.yaml': '- x\n', + }); + try { + await lint({ cwd: root, fix: true }); + const after = fs.readFileSync(path.join(root, 'docs/x.md'), 'utf-8'); + expect(after).toContain('x-foo: 1'); + expect(after).not.toContain('\nfoo: 1'); + } finally { + rmRepo(root); + } +}); diff --git a/test/utils/containment.test.js b/test/utils/containment.test.js index dd7e1d9..bd9cd4e 100644 --- a/test/utils/containment.test.js +++ b/test/utils/containment.test.js @@ -17,6 +17,22 @@ test('containment allows a path that does not exist yet under a real directory', } }); +test('a symlink refusal names the path under the base the caller passed', () => { + const root = makeRepo({ 'reference/Real/pets/listpets.md': 'keep' }); + const viaLink = path.join(path.dirname(root), `rdme-cli-link-${path.basename(root)}`); + fs.symlinkSync(root, viaLink); + fs.symlinkSync(path.join(root, 'reference/Real'), path.join(root, 'reference/Pets')); + try { + const base = path.join(viaLink, 'reference'); + const assertContained = makeContainment(base); + const symlink = path.join(base, 'Pets'); + expect(() => assertContained(path.join(symlink, 'pets/listpets.md'))).toThrow(symlink); + } finally { + fs.unlinkSync(viaLink); + rmRepo(root); + } +}); + test('containment refuses a symlink even when its target is inside the base', () => { const root = makeRepo({ 'reference/Real/pets/listpets.md': 'keep',