Skip to content

Commit f3e37e2

Browse files
fix(frontmatter): prevent code execution in skill and command metadata
<!-- coderabbit-ai-generated:v1 -->
1 parent b140824 commit f3e37e2

6 files changed

Lines changed: 122 additions & 7 deletions

File tree

‎src/services/command/__tests__/frontmatter-commands.spec.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,33 @@ describe("Command loading with frontmatter", () => {
2222
vi.clearAllMocks()
2323
})
2424

25+
it.each(["", "yaml", "json", "js", "javascript"])("restricts both command loaders for %s", async (language) => {
26+
const probe = vi.fn()
27+
vi.stubGlobal("frontmatterProbe", probe)
28+
const unsafe = ["js", "javascript"].includes(language)
29+
const metadata = unsafe
30+
? '(globalThis.frontmatterProbe(), {description: "Example"})'
31+
: language === "json"
32+
? '{"description":"Example"}'
33+
: "description: Example"
34+
const content = `---${language}\n${metadata}\n---\nBody`
35+
mockFs.stat = vi.fn().mockResolvedValue({ isDirectory: () => true })
36+
mockFs.readdir = vi.fn().mockResolvedValue([{ name: "example.md", isFile: () => true }])
37+
mockFs.readFile = vi.fn().mockResolvedValue(content)
38+
try {
39+
const command = await getCommand("/test/cwd", "example")
40+
const commands = await getCommands("/test/cwd")
41+
for (const result of [command, ...commands]) {
42+
expect(result?.description).toBe(unsafe ? undefined : "Example")
43+
expect(result?.content).toBe(unsafe ? content : "Body")
44+
}
45+
expect(commands).toHaveLength(1)
46+
expect(probe).not.toHaveBeenCalled()
47+
} finally {
48+
vi.unstubAllGlobals()
49+
}
50+
})
51+
2552
describe("getCommand with frontmatter", () => {
2653
it("should load command with description from frontmatter", async () => {
2754
const commandContent = `---

‎src/services/command/commands.ts‎

Lines changed: 3 additions & 3 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 { parseFrontmatter } from "../../utils/frontmatter"
55
import { getGlobalRooDirectory, getProjectRooDirectoryForCwd } from "../roo-config"
66
import { getBuiltInCommands, getBuiltInCommand } from "./built-in-commands"
77

@@ -221,7 +221,7 @@ async function tryLoadCommand(
221221

222222
try {
223223
// Try to parse frontmatter with gray-matter
224-
parsed = matter(content)
224+
parsed = parseFrontmatter(content)
225225
description =
226226
typeof parsed.data.description === "string" && parsed.data.description.trim()
227227
? parsed.data.description.trim()
@@ -306,7 +306,7 @@ async function scanCommandDirectory(
306306

307307
try {
308308
// Try to parse frontmatter with gray-matter
309-
parsed = matter(content)
309+
parsed = parseFrontmatter(content)
310310
description =
311311
typeof parsed.data.description === "string" && parsed.data.description.trim()
312312
? 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 { parseFrontmatter } 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 } = parseFrontmatter(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 } = parseFrontmatter(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 } = parseFrontmatter(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: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,40 @@ describe("SkillsManager", () => {
178178
})
179179

180180
describe("discoverSkills", () => {
181+
it.each(["", "yaml", "json", "js", "javascript"])("restricts skill parsing for %s", async (language) => {
182+
mockDirectoryExists.mockImplementation(async (dir: string) => dir === projectSkillsDir)
183+
mockRealpath.mockImplementation(async (dir: string) => dir)
184+
mockReaddir.mockResolvedValue(["example"])
185+
mockStat.mockResolvedValue({ isDirectory: () => true })
186+
mockFileExists.mockResolvedValue(true)
187+
const probe = vi.fn()
188+
vi.stubGlobal("frontmatterProbe", probe)
189+
const unsafe = ["js", "javascript"].includes(language)
190+
const metadata = unsafe
191+
? '(globalThis.frontmatterProbe(), {name: "example", description: "Example"})'
192+
: language === "json"
193+
? '{"name":"example","description":"Example"}'
194+
: "name: example\ndescription: Example"
195+
mockReadFile.mockResolvedValue(`---${language}\n${metadata}\n---\nBody`)
196+
try {
197+
await skillsManager.discoverSkills()
198+
expect(skillsManager.getAllSkills()).toHaveLength(unsafe ? 0 : 1)
199+
if (!unsafe) {
200+
expect((await skillsManager.getSkillContent("example"))?.instructions).toBe("Body")
201+
mockReadFile.mockResolvedValue("---js\n(globalThis.frontmatterProbe(), {})\n---")
202+
await expect(skillsManager.getSkillContent("example")).rejects.toThrow(
203+
"Unsupported frontmatter language",
204+
)
205+
await expect(skillsManager.updateSkillModes("example", "project", ["code"])).rejects.toThrow(
206+
"Unsupported frontmatter language",
207+
)
208+
}
209+
expect(probe).not.toHaveBeenCalled()
210+
} finally {
211+
vi.unstubAllGlobals()
212+
}
213+
})
214+
181215
it("should discover skills from global directory", async () => {
182216
const pdfSkillDir = p(globalSkillsDir, "pdf-processing")
183217
const pdfSkillMd = p(pdfSkillDir, "SKILL.md")
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { parseFrontmatter } from "../frontmatter"
2+
3+
describe("parseFrontmatter", () => {
4+
it.each(["", "yaml", "yml", "json"])("accepts data language %s", (language) => {
5+
const metadata = language === "json" ? '{"name":"example"}' : "name: example"
6+
expect(parseFrontmatter(`---${language}\n${metadata}\n---\nBody`)).toMatchObject({
7+
data: { name: "example" },
8+
content: "Body",
9+
})
10+
})
11+
12+
it.each(["js", "javascript", "JavaScript", "coffee", "toml", "__proto__"])(
13+
"rejects unsupported language %s before execution",
14+
(language) => {
15+
const probe = vi.fn()
16+
vi.stubGlobal("frontmatterProbe", probe)
17+
try {
18+
for (const prefix of ["", "\uFEFF"]) {
19+
expect(() =>
20+
parseFrontmatter(`${prefix}---${language}\r\n(globalThis.frontmatterProbe(), {})\r\n---`),
21+
).toThrow("Unsupported frontmatter language")
22+
}
23+
expect(probe).not.toHaveBeenCalled()
24+
} finally {
25+
vi.unstubAllGlobals()
26+
}
27+
},
28+
)
29+
30+
it("preserves documents without frontmatter", () => {
31+
expect(parseFrontmatter("# Instructions").content).toBe("# Instructions")
32+
})
33+
34+
it("rejects executable YAML tags", () => {
35+
expect(() => parseFrontmatter('---\nvalue: !!js/function "function () {}"\n---')).toThrow()
36+
})
37+
})

‎src/utils/frontmatter.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import matter from "gray-matter"
2+
3+
/** Parse untrusted metadata without allowing document-selected executable engines. */
4+
export function parseFrontmatter(content: string) {
5+
// Match gray-matter's BOM normalization before inspecting its language marker.
6+
const normalized = content.replace(/^\uFEFF/, "")
7+
if (normalized.startsWith("---") && normalized[3] !== "-") {
8+
const { name } = matter.language(normalized.slice(3))
9+
if (name && !["yaml", "yml", "json"].includes(name)) {
10+
throw new Error(`Unsupported frontmatter language: ${name}`)
11+
}
12+
}
13+
14+
// Passing options also bypasses gray-matter's cache of unrestricted parses.
15+
return matter(normalized, { language: "yaml" })
16+
}

0 commit comments

Comments
 (0)