Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(frontmatter): bound YAML aliases in the #6157 whole-block checks (security review)

garrytancd6a1fd18be0
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 2d28bd6e19..4c4ade9123 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`. #6157: `parseMarkdown` (`markdown.ts` `yamlBlockError`) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, and `brain-writer.ts` `autoFixFrontmatter` skips the NESTED_QUOTES rewrite on a parseable block and keeps a tags/aliases re-quote only when the line reads back as the same value, so `validate`, `--fix`, `lint` and `repair frontmatter` never flag or rewrite valid YAML.
+- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`. #6157: `parseMarkdown` (`markdown.ts` `yamlBlockError`) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, and `brain-writer.ts` `autoFixFrontmatter` skips the NESTED_QUOTES rewrite on a parseable block and keeps a tags/aliases re-quote only when the line reads back as the same value, so `validate`, `--fix`, `lint` and `repair frontmatter` never flag or rewrite valid YAML. A block (or tags/aliases line) with more than `MAX_FRONTMATTER_YAML_ALIASES` (16) aliases outside quotes counts as not parsing and is never rewritten (`yamlAliasesWithinLimit`; alias-bomb guard, `test/frontmatter-alias-bomb.test.ts`).
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).
diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.ts
index 277f4ede63..7105aea5c2 100644
--- a/src/core/brain-writer.ts
+++ b/src/core/brain-writer.ts
@@ -31,6 +31,7 @@ import {
type ParseValidationCode,
type ParseValidationError,
type ParseWarningCode,
+ yamlAliasesWithinLimit,
yamlBlockError,
} from './markdown.ts';
import { isMarkdownFilePath, isSyncable, pruneDir, slugifyPath } from './sync.ts';
@@ -156,9 +157,11 @@ export function createFrontmatterBackup(filePath: string, opts: FrontmatterBacku
/**
* A cosmetic line rewrite is kept only when it reads back as the same value
* (#6157). A line that does not parse on its own is a repair target, so the
- * rewrite is allowed.
+ * rewrite is allowed. A line over the alias limit is never rewritten: its
+ * value could expand exponentially when compared.
*/
function rewriteKeepsYamlValue(before: string, after: string): boolean {
+ if (!yamlAliasesWithinLimit(before)) return false;
let original: unknown;
try {
original = yamlLoad(before);
@@ -336,7 +339,8 @@ export function autoFixFrontmatter(
for (let i = firstNonEmpty + 1; i < lines.length; i++) {
if (lines[i].trim() === '---') { closeIdx = i; break; }
}
- const blockParses = closeIdx < lines.length && yamlBlockError(lines.slice(firstNonEmpty + 1, closeIdx).join('\n')) === null;
+ const block = lines.slice(firstNonEmpty + 1, closeIdx).join('\n');
+ const blockParses = closeIdx < lines.length && yamlBlockError(block) === null && yamlAliasesWithinLimit(block);
let fixedAny = false;
for (let i = firstNonEmpty + 1; !blockParses && i < closeIdx; i++) {
const m = lines[i].match(/^(\s*[A-Za-z_][\w-]*\s*:\s*)"(.*)"\s*(.*)$/);
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index b50b9bd678..4087c0c2cd 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -651,8 +651,10 @@ function collectValidationErrors(
// #6157: parse the whole block once. The per-line NESTED_QUOTES heuristic
// below only runs when the block fails to parse; a block-scalar
- // continuation line that looks like `Key: "a", "b"` is valid YAML.
+ // continuation line that looks like `Key: "a", "b"` is valid YAML. A block
+ // over the alias limit counts as not parsing (the heuristics apply).
const blockParseError = yamlBlockError(fmBody);
+ const blockParses = blockParseError === null && yamlAliasesWithinLimit(fmBody);
// 5. NESTED_QUOTES — common breakage pattern: `title: "Name "Nick" Last"`.
// The heuristic: a frontmatter `key: value` line with 3+ unescaped
@@ -663,7 +665,7 @@ function collectValidationErrors(
// Disambiguate by running js-yaml on just the value; only flag
// lines that genuinely fail to parse. The full-frontmatter YAML
// parse error is caught separately by check 6 (YAML_PARSE) below.
- for (let i = firstNonEmpty + 1; blockParseError && i < closeLine; i++) {
+ for (let i = firstNonEmpty + 1; !blockParses && i < closeLine; i++) {
const line = lines[i];
const m = line.match(/^\s*[A-Za-z_][\w-]*\s*:\s*(.*)$/);
if (!m) continue;
@@ -748,6 +750,23 @@ function collectValidationErrors(
}
}
+/**
+ * Most YAML aliases (`*name`) a frontmatter block may hold before the #6157
+ * whole-block checks treat it as not parsing. Frontmatter is untrusted: a few
+ * hundred bytes of nested `&a [*b, *b]` anchors expand exponentially once the
+ * parsed value is walked (compared, stringified). Real frontmatter rarely
+ * uses aliases at all.
+ */
+export const MAX_FRONTMATTER_YAML_ALIASES = 16;
+
+/** False when the text holds more than MAX_FRONTMATTER_YAML_ALIASES aliases outside quoted strings. */
+export function yamlAliasesWithinLimit(text: string): boolean {
+ const unquoted = text.replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\n]|'')*'/g, '');
+ let count = 0;
+ for (const _ of unquoted.matchAll(/(?:^|[\s,[{])\*[^\s,[\]{}]/g)) if (++count > MAX_FRONTMATTER_YAML_ALIASES) return false;
+ return true;
+}
+
/** The js-yaml error for a frontmatter block, or null when the whole block parses. */
export function yamlBlockError(block: string): Error | null {
try {
diff --git a/test/frontmatter-alias-bomb.test.ts b/test/frontmatter-alias-bomb.test.ts
new file mode 100644
index 0000000000..9d75b98dab
--- /dev/null
+++ b/test/frontmatter-alias-bomb.test.ts
@@ -0,0 +1,50 @@
+/**
+ * Security review (fix wave 11, W5.1): frontmatter is untrusted input. A YAML
+ * alias bomb (a few hundred bytes of nested `&a [*b, *b]` anchors) expands
+ * exponentially when its parsed value is walked. The whole-block checks added
+ * for #6157 must treat a block with more aliases than the limit as "does not
+ * parse": the per-line heuristics apply as before and nothing on that path is
+ * rewritten. Valid folded YAML still validates clean and is left untouched.
+ * Pure: parseMarkdown / autoFixFrontmatter, no DB.
+ */
+import { describe, expect, test } from 'bun:test';
+import { autoFixFrontmatter } from '../src/core/brain-writer.ts';
+import { parseMarkdown, yamlAliasesWithinLimit } from '../src/core/markdown.ts';
+
+const fence = '---';
+function bomb(key: string, depth = 26): string {
+ let items = `&l0 ["x", "x"]`;
+ for (let i = 1; i < depth; i++) items += `, &l${i} [*l${i - 1}, *l${i - 1}]`;
+ return `${key}: [${items}]`;
+}
+const page = (line: string) => `${fence}\ntype: note\ntitle: x\n${line}\n${fence}\n\nbody`;
+
+describe('frontmatter alias bomb (W5.1 security review)', () => {
+ for (const key of ['tags', 'aliases', 'related']) {
+ test(`autoFixFrontmatter returns fast and rewrites nothing on a ${key}: bomb`, () => {
+ const input = page(bomb(key));
+ const started = performance.now();
+ const { content } = autoFixFrontmatter(input);
+ expect(performance.now() - started).toBeLessThan(1000);
+ expect(content).toBe(input);
+ });
+ }
+
+ test('validation of a bomb in a non-tag key returns fast', () => {
+ const started = performance.now();
+ parseMarkdown(page(bomb('related')), undefined, { validate: true });
+ expect(performance.now() - started).toBeLessThan(1000);
+ });
+
+ test('the alias limit counts aliases outside quotes only', () => {
+ expect(yamlAliasesWithinLimit(bomb('tags'))).toBe(false);
+ expect(yamlAliasesWithinLimit('base: &b {a: 1}\nother: *b\nnote: "a *star* in a string"')).toBe(true);
+ expect(yamlAliasesWithinLimit(`quote: "${'*a '.repeat(40)}"`)).toBe(true);
+ });
+
+ test('valid folded YAML still passes and is left byte-identical', () => {
+ const input = `${fence}\ntype: concept\ntitle: Notes\nclaim: >-\n The founder said\n Reply: "Ship it", then "measure it" twice\n${fence}\n\nbody`;
+ expect(parseMarkdown(input, undefined, { validate: true }).errors!.filter(e => e.code === 'NESTED_QUOTES' || e.code === 'YAML_PARSE')).toHaveLength(0);
+ expect(autoFixFrontmatter(input).content).toBe(input);
+ });
+});