Skip to content

fix(security): add host/origin allowlist + validate git refs + quote workflow input - #2185

Merged
affaan-m merged 1 commit into
affaan-m:mainfrom
aaronjmars:security/control-pane-host-validation
Jun 15, 2026
Merged

affaan-m merged 1 commit into
affaan-m:mainfrom
aaronjmars:security/control-pane-host-validation

Conversation

@aaronjmars

@aaronjmars aaronjmars commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Three defense-in-depth fixes around untrusted input flowing to subprocess execution. None of the affected paths had a direct attacker-reachable proof of exploit, but each one combines a published threat-model boundary (loopback-only, model-supplied tool args, CI input boundary) with the kind of pattern that has bit other agent-tooling projects in the same week. Net effect: an attacker who can pivot through DNS-rebinding, prompt-inject the agent's tool args, or pass attacker-controlled inputs into a downstream caller of the reusable workflow can no longer reach a shell.

Impact

1. Control-pane HTTP server — DNS-rebinding gate. scripts/lib/control-pane/server.js binds to 127.0.0.1:8765 by default and exposes POST /api/actions/:id, which spawns cargo run -- graph <subcommand> with a request-body-supplied query and limit. The handler did not validate the Host or Origin header, so a victim visiting attacker.example (DNS-rebound to 127.0.0.1) would trigger same-origin POSTs to the loopback API, ultimately invoking recall-knowledge / sync-knowledge / graph-sync with attacker-shaped strings. /api/snapshot is similarly reachable for read-side exfiltration of the graph DB summary.

2. OpenCode gitSummary tool — model-supplied shell input. .opencode/tools/git-summary.ts was building git diff ${baseBranch}...HEAD --stat with execSync, where baseBranch is a string tool argument the LLM picks. An attacker who can prompt-inject the agent (untrusted file content, README, PR body, etc.) can drive the model to pass baseBranch = 'main"; <payload>; echo "x' and reach RCE on the developer's machine.

3. Reusable test workflow — script-injection seam. .github/workflows/reusable-test.yml interpolated ${{ inputs.package-manager }} directly into a bash case and into an unsupported-PM echo. The repo's own caller (ci.yml) constrains matrix.pm to a fixed set, but downstream callers of the reusable workflow that forward attacker-controllable input (e.g. an issue_comment-triggered workflow) would inject into the runner shell.

Location

  • scripts/lib/control-pane/server.js:163-205 (handler) + new helpers at the top of the file
  • .opencode/tools/git-summary.ts:30-65
  • .github/workflows/reusable-test.yml:64-81

Fix

  • Control-pane: Build an allowedHostnames set at server start containing the configured --host plus loopback variants (127.0.0.1, localhost, [::1], ::1). Reject mismatched Host headers with 421 Misdirected Request and non-loopback Origin headers (when present) with 403 Forbidden origin before any route handler runs. Host is mandatory; Origin is optional so non-browser clients (fetch from node, curl) still work.
  • OpenCode tool: Swap execSync for execFileSync with an args-array form so no spawned git call passes through a shell. Validate baseBranch against ^[A-Za-z0-9._/-]+$ plus the usual git-ref guardrails (no leading -/.//, no embedded .. or //, max 200 chars). Clamp depth to a positive integer ≤ 1000 before interpolating into -N.
  • Workflow: Move ${{ inputs.package-manager }} into a PACKAGE_MANAGER step env var and reference $PACKAGE_MANAGER inside the script, per the canonical GitHub script-injection mitigation.

Detected by

Aeon + Semgrep p/security-audit, surfaced via the threat-model-claim manual-review axis (SECURITY.md scopes "Local MCP Ports" verification but not the control-pane HTTP server one floor up; tool-args boundary advertised by OpenCode's tool schema but not enforced at the execSync call site; reusable workflow advertised as composable but unguarded against caller-supplied input).

  • Severity: medium-high (DNS-rebinding gate), medium-high (prompt-injection → RCE via tool args), low-medium (dormant CI surface, easy to enable accidentally)
  • CWE-918 (server-side request forgery class via DNS rebinding) / CWE-352 (CSRF-equivalent in absence of Host check) / CWE-78 (OS command injection — opencode tool + workflow)
  • No published advisory; this PR is the disclosure.

Verification

node tests/run-all.js — 2686 / 2687 passing. The one failure (observe.sh falls back to legacy output fields when tool_response is null, in tests/hooks/hooks.test.js) reproduces on main without this branch applied and is unrelated. npx eslint scripts/**/*.js tests/**/*.js clean. node scripts/ci/validate-workflow-security.js clean.

Two new tests added in tests/scripts/control-pane.test.js:

  • classifies Host and Origin headers against the loopback allowlist — unit test of the classifier against forged and legitimate hostnames including IPv6 / case-insensitive matching and a non-default --host LAN binding.
  • rejects requests forged with a non-loopback Host header (DNS rebinding gate) — end-to-end test against a live server using http.request to send forged Host and Origin headers, asserts 421 / 403 and that the legitimate baseline still returns 200.

Filed by Aeon.


Summary by cubic

Strengthens input handling to block DNS rebinding and command/script injection across the control-pane server, the git-summary tool, and the reusable CI workflow. Removes shell entry points and restricts loopback access to prevent untrusted input from reaching a shell.

  • Bug Fixes
    • Control-pane HTTP server: Allowlist Host/Origin to loopback and the configured --host; reject others with 421/403 before routing. Origin remains optional for non-browser clients. (scripts/lib/control-pane/server.js)
    • OpenCode git-summary tool: Replace execSync with execFileSync (args array), validate baseBranch as a safe git ref, and clamp depth to a small positive int. Protects log, staged diff, and branch diff calls. (.opencode/tools/git-summary.ts)
    • Reusable test workflow: Move ${{ inputs.package-manager }} into PACKAGE_MANAGER env and reference $PACKAGE_MANAGER in the script to prevent shell injection. (.github/workflows/reusable-test.yml)

Written for commit 56bd1bd. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Bug Fixes

    • Restricted control-pane HTTP API access to exclusively local connections. Requests from external hosts or non-loopback origins are now rejected with appropriate HTTP error responses.
  • Chores

    • Enhanced input validation in internal git utilities to prevent unsafe git reference injection.
    • Updated GitHub Actions reusable test workflow for improved package manager selection.
  • Tests

    • Added comprehensive test coverage for control-pane security features.

…workflow input

Three defense-in-depth fixes around untrusted input flowing to subprocess execution:

1. **Control-pane HTTP server (scripts/lib/control-pane/server.js)**
   The local control-pane API binds to 127.0.0.1 but had no Host or Origin
   validation, so a DNS-rebinding attack from a malicious website could pivot
   into the loopback endpoints — including POST /api/actions/:id, which spawns
   'cargo run -- graph ...' with caller-supplied query strings. Add a hostname
   allowlist (loopback variants plus the explicitly configured --host) and
   reject mismatched Host (421) or non-loopback Origin (403) before any route
   handler runs.

2. **OpenCode git-summary tool (.opencode/tools/git-summary.ts)**
   The tool was building 'git diff ${baseBranch}...HEAD --stat' with execSync
   and a raw model-supplied baseBranch string. Switch run() to execFileSync
   with an args array (no shell), validate baseBranch against a conservative
   git-ref allowlist (rejects shell metacharacters, leading -, embedded ..),
   and clamp the depth arg to a small positive integer before interpolating
   into 'git log --oneline -<N>'.

3. **Reusable test workflow (.github/workflows/reusable-test.yml)**
   The 'Install dependencies' step interpolated ${{ inputs.package-manager }}
   directly into a bash 'case' and into an echo, so a downstream caller that
   forwarded attacker-controllable input could inject into the runner. Move
   the input into a PACKAGE_MANAGER env var and reference $PACKAGE_MANAGER
   inside the script per the GitHub script-injection guidance.

Detected by Aeon + semgrep p/security-audit (host check via threat-model
manual-review axis; git-summary via detect-child-process; workflow via
run-shell-injection).

Verification: node tests/run-all.js — 2686/2687 pre-existing tests pass; the
one failure (observe.sh legacy output fallback) reproduces on main without
this branch applied. Added 2 new control-pane tests covering the allowlist
classifier and the DNS-rebinding-gate behavior end-to-end.

---
Filed by [Aeon](https://github.com/aaronjmars/aeon-aaron).
@aaronjmars
aaronjmars requested a review from affaan-m as a code owner June 7, 2026 08:26
@ecc-tools

ecc-tools Bot commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds three independent security and robustness improvements: a package-manager variable refactoring in the CI workflow, input validation and safer command execution in the git-summary tool, and HTTP request allowlisting for the control-pane server with matching test coverage.

Changes

Package Manager Variable Refactoring

Layer / File(s) Summary
Shell variable for package manager selection
.github/workflows/reusable-test.yml
Package-manager input is extracted into a PACKAGE_MANAGER shell variable; the case statement and error message now reference this variable instead of GitHub template syntax.

Git Tool Input Validation and Safer Execution

Layer / File(s) Summary
Input validation helpers for depth and ref safety
.opencode/tools/git-summary.ts
Added SAFE_GIT_REF pattern, isSafeRef(ref) to reject unsafe ref names, and isSafeDepth(value) to validate commit depth as a bounded positive integer.
Safe execution of git commands with validated inputs
.opencode/tools/git-summary.ts
Tool execution validates depth and conditionally computes branchDiff only when baseBranch passes isSafeRef; git runner replaced with runArgs() that uses execFileSync with argument arrays instead of shell command strings.

Control-Pane HTTP Request Allowlisting

Layer / File(s) Summary
Host and origin validation helpers
scripts/lib/control-pane/server.js
Added loopback hostnames allowlist and helpers: isAllowedHostHeader() parses and validates Host header; isAllowedOrigin() validates Origin; buildAllowedHostnames() constructs allowed set; functions exported from module.
Request gating middleware in HTTP handler
scripts/lib/control-pane/server.js
During request handling, computes allowedHostnames and rejects requests early if Host fails allowlist (returns 421 Misdirected request) or Origin fails allowlist (returns 403 Forbidden origin).
Test coverage for request allowlisting
tests/scripts/control-pane.test.js
Unit test validates allowlist decisions for loopback/non-loopback hosts and origins including missing Origin; integration test forges requests with non-loopback Host (expects 421) and forged Origin (expects 403), confirming legitimate loopback requests succeed (200).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Three layers of care, we build with grace,
Workflows and tools in their proper place,
Git commands safe, HTTP gated tight,
Loopback requests shine with proper light! 🛡️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately and concisely summarizes all three main security fixes: host/origin allowlisting, git ref validation, and workflow input quoting.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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 and usage tips.

@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.

🧹 Nitpick comments (2)
.opencode/tools/git-summary.ts (1)

70-76: 💤 Low value

Consider optional debug logging for failed git commands.

The empty-string fallback is a reasonable graceful-degradation strategy for tooling, and calling code handles it well. For debugging difficult environments (missing git, permission issues), you could optionally log to stderr at debug level, though this is not blocking.

💡 Optional: Add debug visibility
 function runArgs(args: string[], cwd: string): string {
   try {
     return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim()
-  } catch {
+  } catch (err) {
+    // Uncomment for debugging: console.error(`git ${args[0]} failed:`, err)
     return ""
   }
 }
🤖 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 @.opencode/tools/git-summary.ts around lines 70 - 76, The runArgs function
swallows all errors and returns an empty string; add optional debug logging in
the catch to surface the underlying error when debug mode is enabled. Modify
runArgs to accept or read a debug flag (or use an existing logger) and in the
catch block log a debug-level message containing the args, cwd and the caught
error before returning ""; reference the runArgs function and the execFileSync
call so the change is limited to that function's catch handling.
scripts/lib/control-pane/server.js (1)

12-12: Add IPv4-mapped IPv6 loopback hostnames to LOOPBACK_HOSTNAMES

scripts/lib/control-pane/server.js currently allows only 127.0.0.1, localhost, [::1], and ::1. On dual-stack systems, local connections may present ::ffff:127.0.0.1; parseHostHeader() expects the bracketed form for Host ([::ffff:127.0.0.1]), while isAllowedOrigin() expects the unbracketed form for Origin (::ffff:127.0.0.1). Adding both to the allowlist (or normalizing ::ffff:127.0.0.1 → 127.0.0.1) avoids incorrectly rejecting local requests with 421/403.

🤖 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 `@scripts/lib/control-pane/server.js` at line 12, LOOPBACK_HOSTNAMES currently
lacks IPv4-mapped IPv6 entries, causing local dual-stack requests like
::ffff:127.0.0.1 to be rejected; update the allowlist used by parseHostHeader()
and isAllowedOrigin() by adding both the bracketed and unbracketed IPv4-mapped
forms (e.g. '[::ffff:127.0.0.1]' and '::ffff:127.0.0.1') or normalize mapped
addresses to '127.0.0.1' before checks; modify the Set named LOOPBACK_HOSTNAMES
to include these entries (or add a small normalization helper called from
parseHostHeader() and isAllowedOrigin()) so local dual-stack requests are
accepted.
🤖 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.

Nitpick comments:
In @.opencode/tools/git-summary.ts:
- Around line 70-76: The runArgs function swallows all errors and returns an
empty string; add optional debug logging in the catch to surface the underlying
error when debug mode is enabled. Modify runArgs to accept or read a debug flag
(or use an existing logger) and in the catch block log a debug-level message
containing the args, cwd and the caught error before returning ""; reference the
runArgs function and the execFileSync call so the change is limited to that
function's catch handling.

In `@scripts/lib/control-pane/server.js`:
- Line 12: LOOPBACK_HOSTNAMES currently lacks IPv4-mapped IPv6 entries, causing
local dual-stack requests like ::ffff:127.0.0.1 to be rejected; update the
allowlist used by parseHostHeader() and isAllowedOrigin() by adding both the
bracketed and unbracketed IPv4-mapped forms (e.g. '[::ffff:127.0.0.1]' and
'::ffff:127.0.0.1') or normalize mapped addresses to '127.0.0.1' before checks;
modify the Set named LOOPBACK_HOSTNAMES to include these entries (or add a small
normalization helper called from parseHostHeader() and isAllowedOrigin()) so
local dual-stack requests are accepted.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 009ed015-18bf-418c-a16c-451199d18003

📥 Commits

Reviewing files that changed from the base of the PR and between 90dfd95 and 56bd1bd.

📒 Files selected for processing (4)
  • .github/workflows/reusable-test.yml
  • .opencode/tools/git-summary.ts
  • scripts/lib/control-pane/server.js
  • tests/scripts/control-pane.test.js

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 4 files

Re-trigger cubic

@alexraphael07-prog

Copy link
Copy Markdown

🤖 Bezalel Engine — Automated Code Review

PR #2185 Code Review

1. Summary

Three defense-in-depth security fixes:

  1. Workflow injection hardening — moves inputs.package-manager into an env var before the case statement to prevent expression injection in GitHub Actions
  2. Git ref validation — replaces execSync with execFileSync and adds an allowlist validator for model-supplied git refs (baseBranch)
  3. Depth sanitization — validates the depth parameter is a safe integer before use

These are legitimate, well

@affaan-m
affaan-m merged commit 1c3280d into affaan-m:main Jun 15, 2026
2 checks passed
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.

3 participants