Skip to content

fix(config): compare prototype key guards literally so analysis can see them#1425

Merged
clay-good merged 3 commits into
mainfrom
fix/codeql-prototype-guards
Jul 22, 2026
Merged

fix(config): compare prototype key guards literally so analysis can see them#1425
clay-good merged 3 commits into
mainfrom
fix/codeql-prototype-guards

Conversation

@clay-good

@clay-good clay-good commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Status: Follow-up to #1415, found while sanity-checking main after the merge.

What was wrong

#1415 guarded the config key helpers, and the guards work — Object.prototype is never touched. But the check delegates to a helper doing a Set lookup, which CodeQL cannot follow as a sanitizer.

The result: three prototype-pollution alerts stayed open on src/core/config-schema.ts after #1415 merged, pointing at the exact code that PR hardened. Anyone reading the security dashboard sees "prototype pollution in shipped source" — the thing we told #1414 was fixed.

How it was fixed

The segments are compared literally, in the same function:

for (const key of keys) {
  if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
    return;
  }
}

The check still covers the whole path before anything is written, so a rejected key leaves the object untouched.

Also tightens test/commands/feedback.test.ts, which matched the issue URL with .includes(...) — CodeQL rated that high. It now parses the URL and compares origin and pathname, so a lookalike host cannot satisfy the assertion.

A regression caught in review

The first attempt moved the guard into the write loop. That changed behavior: a path whose unsafe segment follows a safe one created intermediate objects for the safe prefix before bailing.

setNestedValue({a:'x'}, 'b.constructor.c', v)
  before this PR:  {a:'x'}          ← rejected before mutating
  first attempt:   {a:'x', b:{}}    ← partial write left behind

A differential run against the implementation on main caught it: 47,782 mismatches in 400,000 cases. The current form scans the whole path first and re-runs clean.

Proof

Check Result
Differential vs the implementation on main 400,000 cases, 0 mismatches, prototype never polluted
Test suite 2183 pass, 111 files
Guard still holds __proto__.polluted, constructor.prototype.x, featureFlags.__proto__, prototype.y
Build / lint clean (one pre-existing warning, untouched)

Notes

  • Whether CodeQL actually clears the three alerts is not verifiable before merge: default setup exposes no per-ref alert data for branch, head, or merge refs. If they persist, the fallback is dismissing them with justification — the code is provably safe either way.
  • 25 js/shell-command-injection-from-environment alerts remain, all in test/ where execSync interpolates a constant test path. They do not ship. Converting them to execFileSync is mechanical but touches many call sites, so it deserves its own PR.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Strengthened protections for nested configuration updates and deletions to block unsafe key paths containing reserved object keys before any write/delete occurs, while keeping behavior unchanged for valid keys.
  • Tests
    • Improved the formatted feedback output test to parse and validate the first logged https://github.com/Fission-AI/OpenSpec/issues/new URL origin/path.
    • Added coverage to ensure unsafe paths never mutate the target object and do not alter the prototype.

The guards added in #1415 are effective — Object.prototype is never
touched — but they sit at the top of the function and delegate to a Set
lookup, which CodeQL cannot follow. Three prototype-pollution alerts stayed
open on src/core/config-schema.ts after that PR merged, on exactly the code
it hardened.

Each key segment is now compared literally in the loop that performs the
write. Same behavior for every input, including the empty path and nested
creation; the check is simply local to the danger and visible to a reader
and to the analyzer.

Also tightens a feedback test that matched the issue URL with a substring,
which CodeQL rated high. It now parses the URL and compares origin and
pathname, so a lookalike host cannot satisfy the assertion.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@clay-good
clay-good requested a review from TabishB as a code owner July 22, 2026 19:11
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: be7f4b45-c6b6-45c9-bd15-bc4e7a2bd504

📥 Commits

Reviewing files that changed from the base of the PR and between 95928db and 3ade52b.

📒 Files selected for processing (1)
  • test/core/config-schema.test.ts

📝 Walkthrough

Walkthrough

Nested configuration writes and deletes now perform inline unsafe-key checks before mutation, with regression coverage for unchanged objects and prototype safety. The feedback output test parses the logged URL and validates its exact GitHub origin and pathname.

Changes

Configuration guards

Layer / File(s) Summary
Inline nested key protection
src/core/config-schema.ts, .changeset/analyzer-visible-key-guards.md
setNestedValue and deleteNestedValue compare every path segment against unsafe names before writing or deleting.
Rejected-path regression coverage
test/core/config-schema.test.ts
Tests verify unsafe paths leave objects unchanged and do not re-parent prototypes.

Feedback URL validation

Layer / File(s) Summary
Parsed feedback URL assertion
test/commands/feedback.test.ts
The test parses the first logged HTTP URL and verifies the expected GitHub origin and pathname.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: tabishb

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: literal prototype-key guard comparisons for analyzable protection.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/codeql-prototype-guards

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/core/config-schema.ts`:
- Around line 138-154: Update the path-writing logic around the key iteration in
src/core/config-schema.ts:138-154 to preflight every segment for __proto__,
constructor, and prototype before creating or mutating intermediate objects,
while retaining the inline write-site guard for static analysis. Update
.changeset/analyzer-visible-key-guards.md:5-7 only after this change so its
“behavior is unchanged” claim accurately reflects the removal of partial
mutations.
- Around line 169-186: Update the final-key branch of deleteNestedValue to
verify that key is an own property of current before deleting and returning
true; inherited properties such as toString must return false without reporting
a deletion. Preserve the existing handling for missing keys and nested
traversal.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 588a2285-790d-4e08-a904-91bac03c10fe

📥 Commits

Reviewing files that changed from the base of the PR and between e2f748c and 23e96ca.

📒 Files selected for processing (3)
  • .changeset/analyzer-visible-key-guards.md
  • src/core/config-schema.ts
  • test/commands/feedback.test.ts

Comment thread src/core/config-schema.ts Outdated
Comment thread src/core/config-schema.ts Outdated
Comment on lines 169 to 186
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return false;
}

if (i === keys.length - 1) {
if (key in current) {
delete current[key];
return true;
}
return false;
}

if (current[key] === undefined || current[key] === null || typeof current[key] !== 'object') {
return false;
}
current = current[key] as Record<string, unknown>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Check for an own property before reporting deletion success.

key in current includes inherited properties. For example, deleteNestedValue({}, 'toString') returns true even though no configuration key was removed, causing src/commands/config.ts to save unchanged data and report a successful unset.

Proposed fix
-      if (key in current) {
+      if (Object.prototype.hasOwnProperty.call(current, key)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return false;
}
if (i === keys.length - 1) {
if (key in current) {
delete current[key];
return true;
}
return false;
}
if (current[key] === undefined || current[key] === null || typeof current[key] !== 'object') {
return false;
}
current = current[key] as Record<string, unknown>;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return false;
}
if (i === keys.length - 1) {
if (Object.prototype.hasOwnProperty.call(current, key)) {
delete current[key];
return true;
}
return false;
}
if (current[key] === undefined || current[key] === null || typeof current[key] !== 'object') {
return false;
}
current = current[key] as Record<string, unknown>;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/config-schema.ts` around lines 169 - 186, Update the final-key
branch of deleteNestedValue to verify that key is an own property of current
before deleting and returning true; inherited properties such as toString must
return false without reporting a deletion. Preserve the existing handling for
missing keys and nested traversal.

The first attempt at making the guard analyzer-visible moved the check
into the write loop, which changed behavior: a path whose unsafe segment
came after a safe one created the intermediate objects for the safe prefix
before bailing out. `setNestedValue({a:'x'}, 'b.constructor.c', v)` left
behind `b: {}` where the previous implementation wrote nothing.

A differential run against the implementation on main caught it — 47,782
mismatches in 400,000 cases. The literal comparisons stay, but they now
scan the whole path before any mutation, so a rejected key leaves the
object untouched. Re-run of the same comparison: 0 mismatches.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@clay-good clay-good changed the title fix(config): guard prototype keys at the write, not behind a helper fix(config): compare prototype key guards literally so analysis can see them Jul 22, 2026

@alfred-openspec alfred-openspec left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation fixes the partial-write regression, but the committed tests do not guard it: I moved the unsafe-segment check back into the write loop, reproduced { a: 'x', b: {} } from setNestedValue({ a: 'x' }, 'b.constructor.c', 'v'), and all 78 config-schema tests still passed. Please add a focused regression asserting that a later unsafe segment leaves a prepopulated target completely unchanged; then this is ready to approve.

The fix landed without a test that would fail if the guard moved back into
the write loop, so the regression could return unnoticed. The existing
prototype-pollution tests only assert Object.prototype, and every path they
use starts with an unsafe segment on an empty object, so no intermediate
object is created before the guard trips.

Adds cases that put the unsafe segment after a safe one and assert the
whole target, plus one for a trailing unsafe segment, where the debris is a
re-parented prototype rather than an extra key and a structural comparison
alone would miss it.

Verified by reintroducing the regression: 5 of the new assertions fail
against the buggy build and pass against the fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@alfred-openspec alfred-openspec left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at exact head 3ade52b. The new late-unsafe-segment cases pin the no-partial-mutation contract: the exact earlier write-loop implementation now fails four focused assertions, while the fixed code passes all 107 config/feedback tests and the full exact-head CI, security, and CodeQL matrix.

@clay-good
clay-good added this pull request to the merge queue Jul 22, 2026
Merged via the queue into main with commit 040a869 Jul 22, 2026
16 checks passed
@clay-good
clay-good deleted the fix/codeql-prototype-guards branch July 22, 2026 20:06
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.

2 participants