Skip to content

Commit 204f18f

Browse files
fix(skills): prevent code execution through frontmatter parsing
<!-- coderabbit-ai-generated:v1 -->
1 parent 6843b60 commit 204f18f

4 files changed

Lines changed: 93 additions & 20 deletions

File tree

‎src/services/command/commands.ts‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import fs from "fs/promises"
22
import * as path from "path"
33
import { Dirent } from "fs"
4-
import matter from "gray-matter"
4+
import { parseMarkdownFrontmatter } from "../../utils/frontmatter"
55
import { getGlobalRooDirectory, getProjectRooDirectoryForCwd } from "../roo-config"
66
import { getBuiltInCommands, getBuiltInCommand } from "./built-in-commands"
77

@@ -10,19 +10,6 @@ import { getBuiltInCommands, getBuiltInCommand } from "./built-in-commands"
1010
*/
1111
const MAX_DEPTH = 5
1212

13-
/** Parse command metadata only after rejecting document-selected executable engines. */
14-
function parseCommandFrontmatter(content: string) {
15-
// gray-matter strips a leading BOM before detecting the opening delimiter.
16-
const input = content.replace(/^\uFEFF/, "")
17-
if (matter.test(input)) {
18-
const { name: language } = matter.language(input)
19-
if (language && !["yaml", "yml", "json"].includes(language.toLowerCase())) {
20-
throw new Error(`Unsupported command frontmatter language: ${language}`)
21-
}
22-
}
23-
return matter(content)
24-
}
25-
2613
export interface Command {
2714
name: string
2815
content: string
@@ -234,7 +221,7 @@ async function tryLoadCommand(
234221

235222
try {
236223
// Try to parse frontmatter with gray-matter
237-
parsed = parseCommandFrontmatter(content)
224+
parsed = parseMarkdownFrontmatter(content)
238225
description =
239226
typeof parsed.data.description === "string" && parsed.data.description.trim()
240227
? parsed.data.description.trim()
@@ -319,7 +306,7 @@ async function scanCommandDirectory(
319306

320307
try {
321308
// Try to parse frontmatter with gray-matter
322-
parsed = parseCommandFrontmatter(content)
309+
parsed = parseMarkdownFrontmatter(content)
323310
description =
324311
typeof parsed.data.description === "string" && parsed.data.description.trim()
325312
? parsed.data.description.trim()

‎src/services/skills/SkillsManager.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as fs from "fs/promises"
22
import * as path from "path"
33
import * as vscode from "vscode"
44
import matter from "gray-matter"
5+
import { parseMarkdownFrontmatter } from "../../utils/frontmatter"
56

67
import type { ClineProvider } from "../../core/webview/ClineProvider"
78
import { getGlobalRooDirectory, getGlobalAgentsDirectory, getProjectAgentsDirectoryForCwd } from "../roo-config"
@@ -316,7 +317,7 @@ export class SkillsManager {
316317

317318
try {
318319
// Use gray-matter to parse frontmatter
319-
const { data: frontmatter } = matter(fileContent)
320+
const { data: frontmatter } = parseMarkdownFrontmatter(fileContent)
320321

321322
// Validate required fields (only name and description for now)
322323
if (!frontmatter.name || typeof frontmatter.name !== "string") {
@@ -490,7 +491,7 @@ export class SkillsManager {
490491

491492
// Read skill content from disk
492493
const fileContent = await fs.readFile(skill.path, "utf-8")
493-
const { content: body } = matter(fileContent)
494+
const { content: body } = parseMarkdownFrontmatter(fileContent)
494495

495496
return {
496497
...skill,
@@ -945,7 +946,7 @@ Add your skill instructions here.
945946

946947
// Read the current SKILL.md file
947948
const fileContent = await fs.readFile(skill.path, "utf-8")
948-
const { data: frontmatter, content: body } = matter(fileContent)
949+
const { data: frontmatter, content: body } = parseMarkdownFrontmatter(fileContent)
949950

950951
// Update the frontmatter with new modeSlugs
951952
if (newModeSlugs && newModeSlugs.length > 0) {
@@ -959,7 +960,7 @@ Add your skill instructions here.
959960
}
960961

961962
// Serialize back to SKILL.md format
962-
const newContent = matter.stringify(body, frontmatter)
963+
const newContent = matter.stringify({ content: body }, frontmatter)
963964
await fs.writeFile(skill.path, newContent, "utf-8")
964965

965966
// Refresh skills list

‎src/services/skills/__tests__/SkillsManager.spec.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,77 @@ describe("SkillsManager", () => {
177177
await skillsManager.dispose()
178178
})
179179

180+
describe("frontmatter security", () => {
181+
const skillDir = p(projectSkillsDir, "test-skill")
182+
const skillPath = p(skillDir, "SKILL.md")
183+
const valid = "---\nname: test-skill\ndescription: Test skill\n---\nInstructions"
184+
185+
beforeEach(() => {
186+
mockDirectoryExists.mockImplementation(async (dir: string) => dir === projectSkillsDir)
187+
mockRealpath.mockImplementation(async (value: string) => value)
188+
mockReaddir.mockImplementation(async (dir: string) => (dir === projectSkillsDir ? ["test-skill"] : []))
189+
mockStat.mockResolvedValue({ isDirectory: () => true })
190+
mockFileExists.mockImplementation(async (file: string) => file === skillPath)
191+
mockReadFile.mockResolvedValue(valid)
192+
})
193+
194+
it.each(["javascript", "js", "JavaScript", "coffee", "unknown"])(
195+
"rejects %s at discovery and after the file changes",
196+
async (language) => {
197+
const execute = vi.fn()
198+
vi.stubGlobal("__skillFrontmatterProbe", execute)
199+
try {
200+
await skillsManager.discoverSkills()
201+
const unsafe = `\uFEFF---${language}\n(globalThis.__skillFrontmatterProbe(), {name: "test-skill", description: "Test"})\n---\nBody`
202+
mockReadFile.mockResolvedValue(unsafe)
203+
await expect(skillsManager.getSkillContent("test-skill")).rejects.toThrow("Unsupported frontmatter")
204+
await expect(skillsManager.updateSkillModes("test-skill", "project", ["code"])).rejects.toThrow(
205+
"Unsupported frontmatter",
206+
)
207+
await skillsManager.discoverSkills()
208+
expect(skillsManager.getAllSkills()).toEqual([])
209+
expect(mockWriteFile).not.toHaveBeenCalled()
210+
expect(execute).not.toHaveBeenCalled()
211+
} finally {
212+
vi.unstubAllGlobals()
213+
}
214+
},
215+
)
216+
217+
it.each(["", "yaml", "yml", "json"])(
218+
"accepts data frontmatter %s through all entry points",
219+
async (language) => {
220+
const metadata =
221+
language === "json"
222+
? '{"name":"test-skill","description":"Test skill"}'
223+
: "name: test-skill\ndescription: Test skill"
224+
mockReadFile.mockResolvedValue(`---${language}\n${metadata}\n---\nInstructions`)
225+
await skillsManager.discoverSkills()
226+
expect(skillsManager.getAllSkills()).toHaveLength(1)
227+
await expect(skillsManager.getSkillContent("test-skill")).resolves.toMatchObject({
228+
instructions: "Instructions",
229+
})
230+
await skillsManager.updateSkillModes("test-skill", "project", ["code"])
231+
expect(mockWriteFile).toHaveBeenCalledWith(skillPath, expect.stringContaining("modeSlugs:"), "utf-8")
232+
},
233+
)
234+
235+
it("preserves executable-looking body text during mode updates without parsing it", async () => {
236+
const execute = vi.fn()
237+
vi.stubGlobal("__skillBodyProbe", execute)
238+
try {
239+
const body = "---js\n(globalThis.__skillBodyProbe())\n---\nBody"
240+
mockReadFile.mockResolvedValue(valid.replace("Instructions", body))
241+
await skillsManager.discoverSkills()
242+
await skillsManager.updateSkillModes("test-skill", "project", ["code"])
243+
expect(execute).not.toHaveBeenCalled()
244+
expect(mockWriteFile).toHaveBeenCalledWith(skillPath, expect.stringContaining(body), "utf-8")
245+
} finally {
246+
vi.unstubAllGlobals()
247+
}
248+
})
249+
})
250+
180251
describe("discoverSkills", () => {
181252
it("should discover skills from global directory", async () => {
182253
const pdfSkillDir = p(globalSkillsDir, "pdf-processing")

‎src/utils/frontmatter.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import matter from "gray-matter"
2+
3+
/** Parse Markdown metadata only after rejecting document-selected executable engines. */
4+
export function parseMarkdownFrontmatter(content: string) {
5+
// gray-matter strips a leading BOM before detecting the opening delimiter.
6+
const input = content.replace(/^\uFEFF/, "")
7+
if (matter.test(input)) {
8+
const { name: language } = matter.language(input)
9+
if (language && !["yaml", "yml", "json"].includes(language.toLowerCase())) {
10+
throw new Error(`Unsupported frontmatter language: ${language}`)
11+
}
12+
}
13+
return matter(content)
14+
}

0 commit comments

Comments
 (0)