Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
train K: confine #7830's skillpack child paths with confinedSkillChildWrite instead of annotating them
garrytan82cf2a5b7f7d
diff --git a/src/commands/skillpack/update.ts b/src/commands/skillpack/update.tsindex a2e986f222..9105802b0a 100644--- a/src/commands/skillpack/update.ts+++ b/src/commands/skillpack/update.ts@@ -33,7 +33,7 @@ export const UPDATE_HELP ='2 a skill failed and was rolled back (files touched and restore command printed).';function workspaceSkillsRoot(workspace: string | null): string {- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- workspace is the local operator's own --workspace arg; skillpack update runs only on the trusted local CLI (never MCP/remote)+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- root selection, not a child join: the operator's own --workspace (trusted local CLI only) plus the constant 'skills'; a symlinked skills dir is a supported root, and every child path under it goes through confinedSkillChildWritereturn skillsRootKey(join(resolveWorkspace({ workspace }), 'skills'));}diff --git a/src/core/skillpack/safe-update.ts b/src/core/skillpack/safe-update.tsindex b4cf184556..6a70446aa1 100644--- a/src/core/skillpack/safe-update.ts+++ b/src/core/skillpack/safe-update.ts@@ -197,8 +197,7 @@ export function classifySkill(ctx: ClassifyContext, slug: string): SkillOutcomeoutcome.reason = reason;if (!ctx.noDiff && reason !== 'pinned') {outcome.diffs = changed.filter(f => f.pre !== null).map(f => ({- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- f.rel passed confinedSkillChildWrite in classifySkill (an escaping rel is skipped as unsafe_target before this read)- rel: f.rel, ...boundedRedactedDiff(readFileSync(join(ctx.skillsRoot, f.rel)), readFileSync(f.source), f.rel),+ rel: f.rel, ...boundedRedactedDiff(readFileSync(confinedSkillChildWrite(ctx.skillsRoot, f.rel, { dryRun: true })), readFileSync(f.source), f.rel),}));}return outcome;@@ -226,8 +225,7 @@ export function defaultValidator(skillsRoot: string): (root: string, slug: strin}return (root, slug) => {const problems: string[] = [];- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- slug is a bundled-manifest skill that classified and applied; read-only conformance check- const content = readFileSync(join(root, slug, 'SKILL.md'), 'utf-8');+ const content = readFileSync(confinedSkillChildWrite(root, `${slug}/SKILL.md`, { dryRun: true }), 'utf-8');const fm = content.startsWith('---') ? parseSkillFrontmatter(content) : null;if (!fm?.name) problems.push(`conformance: ${slug}/SKILL.md has no frontmatter with a name`);if (fm?.triggers?.length && !loadSkillTriggerIndex(root).some(e => e.skillPath === `${slug}/SKILL.md` || e.skillPath.endsWith(`/${slug}/SKILL.md`))) {@@ -249,8 +247,7 @@ export function defaultValidator(skillsRoot: string): (root: string, slug: strinfunction removeStaleStages(skillsRoot: string): void {if (!existsSync(skillsRoot)) return;for (const name of readdirSync(skillsRoot)) {- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- name is a direct readdirSync entry of skillsRoot carrying the gbrain stage prefix- if (name.startsWith(STAGE_PREFIX)) rmSync(join(skillsRoot, name), { recursive: true, force: true });+ if (name.startsWith(STAGE_PREFIX)) rmSync(confinedSkillChildWrite(skillsRoot, name, { dryRun: true }), { recursive: true, force: true });}}@@ -284,8 +281,7 @@ async function applySkill(ctx: ApplyContext, outcome: SkillOutcome, js: JournalSreturn { ...outcome, result: 'failed', failure, touched: renamed.map(f => f.rel), rollback_skipped: rollbackSkipped };};mkdirSync(skillsRoot, { recursive: true });- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- constant STAGE_PREFIX under the skills root- const stage = mkdtempSync(join(skillsRoot, STAGE_PREFIX));+ const stage = mkdtempSync(confinedSkillChildWrite(skillsRoot, STAGE_PREFIX, { dryRun: true }));try {const staged: string[] = [];for (const [i, f] of changed.entries()) {@@ -294,8 +290,7 @@ async function applySkill(ctx: ApplyContext, outcome: SkillOutcome, js: JournalSif (f.rel === `${outcome.slug}/SKILL.md` && !parseSkillFrontmatter(bytes.toString('utf-8'))?.name) {return fail(`staged ${f.rel} has no frontmatter with a name`, 'abandoned');}- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- String(i) under the fresh mkdtemp stage directory- const path = join(stage, String(i));+ const path = confinedSkillChildWrite(stage, String(i), { dryRun: true });writeFileSync(path, bytes);staged.push(path);}@@ -307,8 +302,7 @@ async function applySkill(ctx: ApplyContext, outcome: SkillOutcome, js: JournalSwriteJournal(ctx.journal, ctx.backups);try {for (const file of js.files) {- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- file.rel passed confinedSkillChildWrite in classifySkill; the read feeds a hash-verified backup- if (file.pre !== null) file.backup = backupFile(ctx.journal.id, file.rel, join(skillsRoot, file.rel), file.pre, ctx.backups);+ if (file.pre !== null) file.backup = backupFile(ctx.journal.id, file.rel, confinedSkillChildWrite(skillsRoot, file.rel, { dryRun: true }), file.pre, ctx.backups);}} catch (err) {return fail(`changed since classification: ${(err as Error).message}`, 'abandoned');@@ -351,7 +345,7 @@ export async function runSkillpackUpdate(opts: UpdateOptions): Promise<UpdateResconst backups = opts.backups ?? backupsRoot();const manifest = loadBundleManifest(opts.gbrainRoot);const slugs = opts.slugs ?? bundledSkillSlugs(manifest);- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- gbrainRoot is the install's own root (findGbrainOrDie)+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- root selection, not a child join: the install's own root (findGbrainOrDie) plus the constant 'skills'const history = loadVerifiedSkillsLockHistory(join(opts.gbrainRoot, 'skills'));const pending = pendingJournals({ root: backups, skillsRoot: opts.skillsRoot }).map(j => j.id);if (pending.length && !opts.dryRun) {diff --git a/src/core/skillpack/update-journal.ts b/src/core/skillpack/update-journal.tsindex 99a268e62e..28caef500f 100644--- a/src/core/skillpack/update-journal.ts+++ b/src/core/skillpack/update-journal.ts@@ -17,7 +17,7 @@*/import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'fs';import { createHash, randomBytes, randomUUID } from 'crypto';-import { dirname, join } from 'path';+import { dirname } from 'path';import { gbrainPath } from '../config.ts';import { OperationError } from '../ops/contract.ts';@@ -92,23 +92,20 @@ export function journalDir(id: string, root = backupsRoot()): string {throw new OperationError('skillpack_journal_not_found', `'${id}' is not a skillpack backup id.`,'List the backups with gbrain skillpack restore --list.');}- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- id matched the backup-id pattern above (timestamp digits, T, Z, '-' and six hex)- return join(root, id);+ return confinedSkillChildWrite(root, id, { dryRun: true });}export function writeJournal(journal: Journal, root = backupsRoot()): void {const dir = journalDir(journal.id, root);mkdirSync(dir, { recursive: true });- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- dir came from journalDir, which validated the id- const path = join(dir, 'journal.json');+ const path = confinedSkillChildWrite(dir, 'journal.json', { dryRun: true });const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;writeFileSync(tmp, JSON.stringify(journal, null, 2) + '\n', { mode: 0o600 });renameSync(tmp, path);}export function readJournal(id: string, root = backupsRoot()): Journal {- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- journalDir validated the id- const path = join(journalDir(id, root), 'journal.json');+ const path = confinedSkillChildWrite(journalDir(id, root), 'journal.json', { dryRun: true });if (!existsSync(path)) {throw new OperationError('skillpack_journal_not_found', `No skillpack backup '${id}' under ${root}.`,'List the backups with gbrain skillpack restore --list.');@@ -153,8 +150,7 @@ export function pruneJournals(root = backupsRoot(), now = Date.now()): string[]/** Copy `target` into the journal's backup tree and verify the copy hashes to `expected`. */export function backupFile(journalId: string, rel: string, target: string, expected: string, root = backupsRoot()): string {const backupRel = `files/${rel}`;- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rel passed confinedSkillChildWrite during classification; dest stays under the validated journal dir- const dest = join(journalDir(journalId, root), backupRel);+ const dest = confinedSkillChildWrite(journalDir(journalId, root), backupRel, { dryRun: true });mkdirSync(dirname(dest), { recursive: true });copyFileSync(target, dest);if (sha256(readFileSync(dest)) !== expected) throw new Error(`${rel} changed while it was being backed up`);@@ -165,8 +161,7 @@ export function backupFile(journalId: string, rel: string, target: string, expecexport function replaceFile(target: string, bytes: Buffer): void {assertLegacySkillFilesystemWrite(target);mkdirSync(dirname(target), { recursive: true });- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- target passed assertLegacySkillFilesystemWrite; the temp name is pid + UUID in the same directory- const tmp = join(dirname(target), `.gbrain-skillpack-${process.pid}-${randomUUID()}.tmp`);+ const tmp = confinedSkillChildWrite(dirname(target), `.gbrain-skillpack-${process.pid}-${randomUUID()}.tmp`, { dryRun: true });writeFileSync(tmp, bytes);try {renameSync(tmp, target);@@ -188,8 +183,7 @@ export function undoFile(journalId: string, skillsRoot: string, file: JournalFilunlinkSync(target);return true;}- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- file.backup is read from the user's own journal and its bytes are hash-checked against file.pre before any write- const bytes = readFileSync(join(journalDir(journalId, root), file.backup));+ const bytes = readFileSync(confinedSkillChildWrite(journalDir(journalId, root), file.backup, { dryRun: true }));if (sha256(bytes) !== file.pre) {throw new OperationError('skillpack_backup_corrupt', `The backup of ${file.rel} in ${journalId} does not hash to the journal's pre-update hash.`,`Leave ${file.rel} as it is, or compare it with the bundle using gbrain skillpack reference <skill>.`);diff --git a/test/skillpack-safe-update.test.ts b/test/skillpack-safe-update.test.tsindex 8204e23e62..3046f87717 100644--- a/test/skillpack-safe-update.test.ts+++ b/test/skillpack-safe-update.test.ts@@ -17,7 +17,7 @@ import { runScaffold } from '../src/core/skillpack/scaffold.ts';import {DIFF_LINE_CAP, recordScaffoldBases, runSkillpackRestore, runSkillpackUpdate, setSkillPinned, skillsRootKey, type UpdateOptions,} from '../src/core/skillpack/safe-update.ts';-import { listJournals, sha256 } from '../src/core/skillpack/update-journal.ts';+import { journalDir, listJournals, sha256 } from '../src/core/skillpack/update-journal.ts';import { loadState, saveState } from '../src/core/skillpack/state.ts';import {SKILLS_LOCK_HISTORY_FILENAME, SKILLS_MANIFEST_FILENAME, computeSkillsManifest, droppedHistoryEntries, loadVerifiedSkillsLockHistory,@@ -312,6 +312,27 @@ describe('restore', () => {expect([read(env, 'demo/SKILL.md'), read(env, 'demo/references/notes.md'), read(env, 'other/SKILL.md')]).toEqual(snapshot);expect(snapshot[0]).toBe(V1['demo/SKILL.md']);});++ test('refuses a journal whose backup path leaves the journal directory (.. or absolute)', async () => {+ const env = setup();+ await scaffold(env);+ release(env.gbrainRoot, V2);+ const { journal } = await update(env, { slugs: ['demo'] });+ const journalPath = join(env.backups, journal!, 'journal.json');+ const pristine = readFileSync(journalPath, 'utf-8');+ const outside = join(dirname(env.backups), 'outside-canary.md');+ writeFileSync(outside, V1['demo/SKILL.md']);+ for (const escape of ['../../outside-canary.md', outside]) {+ const tampered = JSON.parse(pristine);+ for (const s of tampered.skills) for (const f of s.files) if (f.rel === 'demo/SKILL.md') f.backup = escape;+ writeFileSync(journalPath, JSON.stringify(tampered));+ await expect(runSkillpackRestore({ id: journal!, statePath: env.statePath, backups: env.backups })).rejects.toMatchObject({ code: 'target_escape' });+ expect(read(env, 'demo/SKILL.md')).toBe(V2['demo/SKILL.md']);+ }+ for (const id of ['..', '../escape', outside]) {+ expect(() => journalDir(id, env.backups)).toThrow(expect.objectContaining({ code: 'skillpack_journal_not_found' }));+ }+ });});describe('shared state lock', () => {