Skip to content

fix(distribution): gate record keys so a control character cannot forge a row - #332

Merged
kyle-sexton merged 3 commits into
mainfrom
fix/sync-manifest-gate-inner-keys
Aug 7, 2026
Merged

kyle-sexton merged 3 commits into
mainfrom
fix/sync-manifest-gate-inner-keys

Conversation

@kyle-sexton

@kyle-sexton kyle-sexton commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Summary

A record's own key list was the one payload @tsv emitted unescaped. @tsv
wraps a string containing a control character in double quotes but keeps the
raw character inside, so a mapping key carrying a newline split its logical
row into two physical rows. Where the injected text continued with a recognized
row kind and an empty record-name column, the forged row satisfied
load_manifest_rows' column-count check, reached the case, and indexed an
associative array with the empty name — which Bash refuses outright:

distribution/sync-manifest.sh: line 291: COMPONENT_TAG["$name"]: bad array subscript
distribution/sync-manifest.sh: line 302: TARGET_TAG["$name"]: bad array subscript

Under set -euo pipefail that fires before die can run, so the operator learned
neither the offending record nor the offending key.

The fix gates the rows rather than the subscripts

ckey/tkey are now emitted only for records whose keys pass both a
keys-are-strings check and a control-character check, carried on new
ckstr/tkstr rows. That mirrors cfstr exactly — the shape the files,
requires, managed, and locally-owned payloads already use — and the shell
reads the two booleans in order, reporting <record> keys must be strings and
then <record> keys may not contain control characters before it reads any key
payload.

Both columns are needed. test matches only strings and aborts the entire yq
pass on anything else, so a control-character check alone turns an unquoted 7:
key into a nameless could not read the component catalog. Filtering the control
column through select(tag == "!!str") stops the abort; the separate strings
boolean is what makes the resulting diagnostic accurate.

Without it, a non-string key would still be caught — the ckey payload uses an
unfiltered keys[], so 7 reaches validate_record_keys and is reported as
contains unknown key '7'. That message is misleading rather than absent: yq
renders the integer key as the string 7, so the manifest looks like it declared
an unknown string key when it actually declared a non-string one. The strings
column also keeps collection keys (? [a, b]) out of a ckey row, where a
sequence has no sensible rendering.

Gating at emission makes the forged row impossible, instead of defending each of
the eighteen *["$name"] writes in load_manifest_rows individually. Same
argument as #329: the fix belongs where the hazard originates, not at every site
that could be hit by it.

Two yq behaviors that shaped it, both re-confirmed empirically here:

  • The ckstr columns are bound after the !!map select, not on the
    unconditional ctag row. A keys-derived column on ctag would evaluate
    keys against non-map records and abort the whole pass — gotcha 2 from perf(distribution): validate the manifest in two yq passes, not 274 #320.
  • all over an empty collect returns true, so a record declaring no keys
    (consumer: {}) still emits ckstr true true and still reaches
    validate_record_keys to be rejected for its missing files key. The existing
    component is an empty mapping case covers that and stays green.

Structural backstop

load_manifest_rows additionally rejects any row whose record-name column is
empty. With the gate in place that is unreachable from manifest content, so it
carries the internal error: prefix consistent with the adjacent malformed-row
check, and exists so a future row kind cannot reintroduce the class.

What each diagnostic was before, and is now

Measured on both engines against the contract suite's own base manifest, so these
are observed strings rather than predictions:

input before after
component key forging an empty record name COMPONENT_TAG["$name"]: bad array subscript component 'consumer' keys may not contain control characters
target key forging an empty record name TARGET_TAG["$name"]: bad array subscript target 'beta/two' keys may not contain control characters
component key forging a real record name manifest component pass reported 3 records, expected 2 component 'consumer' keys may not contain control characters
target key forging a real record name manifest target pass reported 3 records, expected 2 target 'beta/two' keys may not contain control characters
component key with a bare newline internal error: malformed manifest row 'plain"' component 'consumer' keys may not contain control characters
component key 7: component 'consumer' contains unknown key '7' component 'consumer' keys must be strings
target key true: target 'beta/two' contains unknown key 'true' target 'beta/two' keys must be strings
component merge key <<: *anchor component 'consumer' contains unknown key '<<' component 'consumer' keys must be strings
unmodified valid manifest Manifest valid: 2 components, 2 targets unchanged, rc=0

The two crashes and the malformed-row internal error are genuine repairs. The
three non-string rows are changed, not repaired — the previous message was
already named, just misleading, because yq renders an integer key as the string
7 and validate_record_keys then reported it as an unknown string key rather
than as a non-string one.

The merge key is the one row where the new message is arguably less specific:
<< carries tag !!merge, so it lands in the non-string bucket, and an author
writing <<: *defaults sees no non-string key in their source. Both engines
reject it either way — YAML merge keys have never been accepted by this schema —
so nothing changes behaviorally, but whether it deserves its own diagnostic is
tracked in #333 rather than papered over here.

The final row is the control that matters most for a gate like this: clean input
still validates, on both engines, identically.

The open hypothesis from #330: refuted

That issue's body flagged, explicitly as untested, that a forged row naming a
real record might not crash but instead overwrite that record's tag and inflate
record_count, potentially letting the fail-loud count assertion pass while a
genuine row was lost. That does not happen. Measured against the pre-fix
engine, both real-record variants exit 1:

error: manifest component pass reported 3 records, expected 2
error: manifest target pass reported 3 records, expected 2

The structural reason is stronger than the counting one. Because @tsv
quote-wraps any value containing a control character, the carrier record
always keeps the opening " and the text up to the newline as part of its own
key — so the carrier unavoidably acquires a bogus key that validate_record_keys
rejects. A forged row cannot be injected without leaving that marker on the
record that carried it. The record_count mismatch above is a second,
independent catch layered on top: the forged row adds to the count while the
separately-read name list is unchanged, and it can never mask a shortfall because
every real record emits exactly one ctag/ttag and none can be suppressed.

So the pre-fix engine was already failing closed for this variant on two grounds;
only the empty-name variant crashed. Recorded here so the issue closes on a
resolved question rather than an open one.

Deliberately out of scope

That issue also observed that distribution/validate-sync-manifest.mjs rejects
these manifests but never runs against the live manifest in CI — referenced only
from the contract suite. Wiring it into the live gate is not in this PR: it
introduces a second source of truth for manifest validity and needs a decision
about which validator is authoritative on disagreement. Filed as #331 rather
than bundled here, so the observation survives #330 closing.

Test plan

Seven regression cases added to distribution/sync-manifest.test.sh, covering
both sides of every shape:

  • component key forges a row with an empty record name
  • target key forges a row with an empty record name
  • component key forges a row naming a real record
  • target key forges a row naming a real record
  • component key is not a string
  • target key is not a string
  • component key with a bare newline is rejected, which additionally asserts the
    output contains neither bad array subscript nor malformed manifest row —
    the two pre-fix failure modes.

Every fixture was run against the pre-fix engine as well, to prove it reaches
the behavior it targets rather than passing vacuously; the before/after table
above is that measurement. A no-op ${var/pattern/replacement} substitution — the
trap found in an earlier PR here — would leave a valid manifest that exits 0 and
fails invalid_case's nonzero assertion, and the unmodified-manifest control row
confirms that baseline is genuinely rc=0.

The yq expressions were also exercised standalone (yq eval -r over crafted
manifests) to confirm they emit ckstr <record> false true for a non-string key,
ckstr <record> true false for a control-character key — both with the ckey
payload suppressed — true true for a clean record and for an empty mapping, and
no ckstr row at all for a non-map record.

Suite — the distribution check runs bash distribution/sync-manifest.test.sh
after npm ci --prefix distribution (so it does not self-skip): 228 assertions
pass, 0 fail
, with the sixteen new assertions landing as [213]–[228]. The
live 34-component / 8-target manifest still validates.

A local Windows run of the same suite against this exact head also completed
clean: exit 0, 213 assertions, the new ones at [198]–[213]. The local
total is lower because the suite skips executable-bit and mode-preserving-
filesystem cases behind uname -s == Linux* gates, not because anything was
skipped or failed.

Known coverage gaps, filed as #333 rather than left implicit: the engine
rejects six non-string key shapes but only 7: and true: are pinned by tests
(1.5:, null:, ? [a, b], ? {p: q}, and << were verified by hand against
the engine). The bare-newline case's assert_not_contains 'bad array subscript'
is also vacuous for its own fixture — that input produced a malformed-row error
pre-fix, never a subscript error — so it stands as a forward-looking guard, not
as evidence.

Lint — shellcheck --rcfile .shellcheckrc clean on both files.

Related

Closes #330.

…ge a row

A record's own key list was the one payload `@tsv` emitted unescaped. Because
`@tsv` keeps a raw newline inside the quotes it adds, a key carrying one split
its logical row into two physical rows. Where the injected text continued with a
recognized row kind and an empty record-name column, the forged row satisfied
`load_manifest_rows`' column-count check and reached the `case`, which then
indexed an associative array with the empty name — something Bash refuses
outright, so the run died with `bad array subscript` under `set -euo pipefail`
before `die` could name anything.

`ckey`/`tkey` are now gated behind new `ckctl`/`tkctl` boolean rows, the same
shape the `files`, `requires`, `managed`, and `locally-owned` payloads already
use: the shell reads the boolean and reports
`<record> keys may not contain control characters` before it reads any key
payload. Gating at the point the rows are emitted makes the forged row
impossible rather than defending each of the eighteen subscript writes.

`load_manifest_rows` additionally rejects a row whose record-name column is
empty. That is unreachable from manifest content once the gate holds, and stays
as the structural backstop for any future row kind.

A bare newline with no forged continuation previously surfaced as
`internal error: malformed manifest row`; it now names the offending record like
every other key violation.

Closes #330

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@cursor

cursor Bot commented Aug 6, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@claude

claude Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Claude finished @kyle-sexton's task in 6m 23s —— View job


Claude's review

  • Gather context (PR body, diff, CLAUDE.md/REVIEW.md)
  • Review distribution/sync-manifest.sh changes
  • Review distribution/sync-manifest.test.sh changes
  • Check REVIEW.md scope split (security lane exclusion)
  • Post final review

No claude-security-review.yml workflow exists in this repo, so per REVIEW.md this lane also applies the security-scope checks (secrets, injection, authz/tenancy). Nothing in this diff introduces a secret, and the yq expressions bind manifest data through jq-style variables rather than string-concatenating untrusted input into anything shell- or process-invoked, so no injection finding there — this PR is itself fixing an injection-adjacent bug (control characters forging a row).

The fix's core design — gating ckey/tkey emission behind ckctl/tkctl booleans, mirroring the existing files/requires/managed/locally-owned shape — is sound, and the "fix at the origin, not at every subscript site" reasoning is well-argued and consistent with #329. The new structural backstop (rejecting an empty record-name column) is correctly placed before the case so it covers every row kind, and its unreachability from real manifest content is correctly reasoned (component/target names are already regex-validated non-empty before load_manifest_rows runs). I traced all four new test fixtures against the fixed code path and they match the claimed diagnostics.

One likely correctness gap — 🔴 Important

distribution/sync-manifest.sh#L210-L212 (and the mirrored #L238-L240 for targets):

["ckctl", $c.key, ($c.value | [keys[] | (test(strenv(CONTROL_RE)) | not)] | all)],
(select($c.value | [keys[] | (test(strenv(CONTROL_RE)) | not)] | all)
  | . as $k | ($k.value | keys[] | ["ckey", $k.key, .])),

This calls test() on each record key directly, with no select(tag == "!!str") guard first. Every other control-character check in this same file gates test() behind exactly that guard — cfstr (L218), crstr (L227), tmstr (L246), tlstr (L255), and the top-level name check (L409–412, via a separate yq_assert for "must be strings" before the control-character yq_assert). That guard exists specifically because yq's test() errors on a non-string node rather than coercing it, which — per this file's own documented "gotcha 2 from #320" — aborts the entire row-generation pass, not just the one bad record.

A component or target map with a non-string key reaches exactly that: e.g. 42: value, or the YAML 1.1 "Norway problem" (on:/yes:/no: parsing as a boolean key) under a component. Pre-PR, keys[] was emitted unconditionally with no test() call, so a non-string key flowed through to validate_record_keys and was rejected cleanly as component '<name>' contains unknown key '42'. Post-PR, that same manifest would (if this reasoning holds) blow up the whole yq eval invocation and surface only could not read the component catalog from the manifest — a worse, less specific diagnostic, and the same class of failure this PR exists to close for other paths.

I wasn't able to execute yq in this sandbox to get an empirical repro (binary invocation is blocked here), so treat this as a strong-but-unverified read grounded in the file's own established idiom rather than a confirmed crash. Worth a quick manual check — yq eval -r '.components.consumer | [keys[] | test("x")]' - against a manifest with an int/bool component key — before merging. If confirmed, the fix is the same guard used everywhere else: select(tag == "!!str") before test(), likely paired with a "keys must be strings" boolean the same way cfstr/crstr pair their two checks.

Minor — test coverage asymmetry — 🟡 Nit

The four new fixtures cover empty-name forgery for both components and targets, but the real-record-name-forgery and bare-newline cases are only exercised for components (ckey), not targets (tkey), even though the code paths are structurally identical. Given how mechanically mirrored COMPONENT_ROW_EXPRESSION/TARGET_ROW_EXPRESSION are, this is a reasonable simplification rather than a real gap, but a target-side bare-newline case would close the symmetry the rest of the suite maintains (e.g. both component key forges... and target key forges... exist for the empty-name variant).

Fix this →

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown

Claude has reviewed this PR 1 time. The lane skips further automatic reviews after 5; deleting this comment resets the count.

kyle-sexton and others added 2 commits August 6, 2026 13:21
…the pass

The key gate introduced in the previous commit tested every key for control
characters without first checking that the key is a string. `test` matches only
strings, so an unquoted `7:`, `true:`, or `1.5:` key aborted the whole yq pass
with `cannot match with !!int`, and the shell reported
`could not read the component catalog` — naming neither the record nor the key.
That is the same nameless-failure shape the gate exists to remove.

The gate now mirrors `cfstr`: one row carries both a keys-are-strings boolean and
a control-character boolean computed over `select(tag == "!!str")`, the key
payload is gated on both, and the shell reports
`<record> keys must be strings` before the control-character check. Filtering
without that first check would instead hide a non-string key from
`validate_record_keys` entirely.

Renamed `ckctl`/`tkctl` to `ckstr`/`tkstr` to match the `cfstr`/`crstr`/`tmstr`/
`tlstr` naming the sibling boolean rows already use.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
The pull_request synchronize event for 40e1e37 was lost, so no workflow runs
exist for that commit. This empty commit re-fires the event.
@kyle-sexton
kyle-sexton merged commit 610b178 into main Aug 7, 2026
1 check passed
@kyle-sexton
kyle-sexton deleted the fix/sync-manifest-gate-inner-keys branch August 7, 2026 07:24
kyle-sexton added a commit that referenced this pull request Aug 11, 2026
…350)

<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
## Summary

- Add merge-key detection so `!!merge` keys emit `merge keys are not
supported` instead of the generic `keys must be strings`.
- Pin the five remaining non-string key shapes in
`distribution/sync-manifest.test.sh`: float, null, sequence complex key,
mapping complex key, and merge key (integer/boolean were already pinned
in #332).
- Remove the vacuous `bad array subscript` assertion from the
bare-newline fixture.

## Test plan

- [x] `bash harness/shell/run-tests.sh
distribution/sync-manifest.test.sh` (key-shape assertions)
- [ ] CI green on merge

## Related

Closes #333

<!-- CURSOR_AGENT_PR_BODY_END -->

<div><a
href="https://cursor.com/agents/bc-e95c74ba-a1a6-4270-b3db-3938d8c4f19e?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-e95c74ba-a1a6-4270-b3db-3938d8c4f19e&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kyle Sexton <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sync-manifest.sh: a control-character mapping key forges a TSV row and crashes load_manifest_rows on an empty record name

1 participant