Skip to content

fix(agent-hooks): parse endpoint file and keep hook secrets off argv (STA-1284) - #7282

Closed
brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/sta-1284-claude-hook-security-triage
Closed

brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/sta-1284-claude-hook-security-triage

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Hardens Orca's managed agent-hook scripts. A security review of the generated claude-hook.sh flagged the endpoint file being sourced (an arbitrary-code-execution vector) and secrets sitting on the curl command line; this closes both concerns, plus a proxy-exfil gap found alongside them. The agent-status feature behaves identically — the HTTP request Orca's local listener receives is byte-for-byte the same as before.

What changed

All shell (sh) and Windows (cmd) hook scripts now go through one shared builder, src/main/agent-hooks/managed-hook-script.ts:

  • Parse, never source — the main fix. The endpoint file (holds the live port/token for the current Orca) is read line-by-line into the four known ORCA_AGENT_HOOK_* variables instead of being sourced (. "$file" / call "%file%"). Values are assigned as literals, so a command substitution written into that path is stored as a string, never executed. This removes the code-execution vector.
  • Payload off argv. The payload — the user's prompt and tool output, the sensitive and potentially large data — is written to a private mktemp (0600) file and posted via --data-urlencode "payload@<file>", so it never appears in ps / /proc/<pid>/cmdline. This also avoids the EDR command-line-length false positive that fix(agent-hooks): keep the hook event payload off the curl command line #4475 addressed.
  • No proxy exfil. --noproxy 127.0.0.1 keeps the loopback POST from being routed through a configured http_proxy / ALL_PROXY.
  • Digits-only port validation, and the Claude hook stays silent on stdout (its stdout would otherwise be appended to the prompt context).

The per-service shell/batch — previously duplicated across ~11 hook services — is consolidated into this one builder.

Why the token stays on argv

The token is sent as a normal -H "X-Orca-Agent-Hook-Token: …" header on the command line, unchanged from main and matching the Windows path. This is a deliberate choice, not an oversight:

  • It is a per-session, loopback-only credential. The worst a leaked token allows is POSTing fake agent-status updates to 127.0.0.1 — cosmetic, with no exfiltration or privilege escalation.
  • A same-user process that could scrape it from ps can already read it from the mode-600 endpoint file, so argv adds no meaningful new reader.
  • The only curl-version-portable way to move a single header off argv is curl's config-file loader (-K), which interprets arbitrary curl directives from its input — putting a low-value credential behind an injection surface (and the input-validation guard needed to fence it off) is the wrong trade. -H @- (header from stdin) is silently dropped by curl < 7.55, which would break agent statuses on older SSH remotes. The high-value data (the payload) is off argv regardless.

Net effect: this PR changes no curl version requirement, and POSIX and Windows now handle the token identically.

Relationship to #4475

#4475 moved the payload off the curl command line to avoid an EDR command-line-length false positive. This PR keeps the payload off argv (via a private temp file) and adds the two things #4475 didn't touch: the endpoint-file sourcing (the code-exec vector) and --noproxy. #4475's EDR rationale is preserved in the shared builder's comments.

Scope

Converted: claude, codex, gemini, cursor, droid, devin, antigravity, grok, kimi, copilot (POSIX side), command-code. Already safe and unchanged: amp / opencode (JS fetch), hermes (Python urllib), and the Windows PowerShell hooks — all already parsed the file and sent the token as an in-process header.

Testing

  • Shared builder suite (managed-hook-script.test.ts) runs the real generated script via /bin/sh against a live listener: endpoint parsed-not-executed, token delivered as a header, payload via temp file, --noproxy bypass, stale-coords refresh, empty-payload skip, non-numeric port rejection, and stdout silence (including the mktemp-failure fail-open path).
  • Multi-shell matrix. Every agent's real generated script exercised under sh / dash / bash against a live listener (delivery, token header, payload integrity, exact stdout, endpoint-not-executed, CRLF tolerance, proxy bypass).
  • SSH relay round-trip. On a throwaway Linux container: a fresh relay deploy SFTP-installs the new scripts, and running the actual installed claude-hook.sh in-container surfaces working → done in the renderer with the correct connectionId.
  • Windows CI. The cmd-path tests (including the codex .cmd end-to-end against a live listener) were run on a windows-latest runner, since the standard PR job is Linux-only.
  • Real Claude Code CLI and in-app dev build from this branch: hooks install and post status correctly across working / waiting / done; Claude usage/limits and account switcher unaffected.
  • typecheck, lint, and the agent-hook suites (400+ tests) pass.

@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR centralizes managed hook script generation in managed-hook-script.ts, adds POSIX and Windows helpers for endpoint parsing and secure curl posting, and includes the new module in the CLI TypeScript config. Hook services for multiple agents switch from inline script assembly to the shared builders, while tests are updated for temp-file payload handling, header-based token sending, non-executing endpoint parsing, and loopback proxy bypass.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the required template sections for Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections, including No visual change for Screenshots, an AI Review Report, a Security Audit summary, and any platform-specific Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title is concise and matches the main change: parsing endpoint files and keeping secrets off argv.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 1

🧹 Nitpick comments (1)
src/main/agent-hooks/managed-hook-script.ts (1)

21-21: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Unescaped literal interpolation into the shell script (defensive-only concern).

emptyPayload.literal is spliced verbatim into a single-quoted shell string (printf '%s' '${emptyPayload.literal}' > ...). Currently only '{}' is passed (antigravity), so there's no live injection, but if a future caller passes a literal containing a single quote, it would break out of the quoted string in the generated script.

🛡️ Optional hardening
-          `  printf '%s' '${emptyPayload.literal}' > "$__orca_payload_file"`,
+          `  printf '%s' ${JSON.stringify(emptyPayload.literal).replace(/'/g, `'\\''`)} > "$__orca_payload_file"`,

Or simpler: assert/validate at the type level that literal never contains a single quote.

Also applies to: 86-93


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 754ef041-e68f-4af1-a274-3a52cf35c30e

📥 Commits

Reviewing files that changed from the base of the PR and between d1bd914 and 0c5da1f17446ce23ddb52027bd7c883823f6313c.

📒 Files selected for processing (19)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/installer-utils.ts
  • src/main/agent-hooks/managed-hook-script.test.ts
  • src/main/agent-hooks/managed-hook-script.ts
  • src/main/agent-hooks/server.test.ts
  • src/main/antigravity/hook-service.test.ts
  • src/main/antigravity/hook-service.ts
  • src/main/claude/hook-service.ts
  • src/main/codex/hook-service.ts
  • src/main/command-code/command-code-managed-script.ts
  • src/main/copilot/hook-service.ts
  • src/main/cursor/hook-service.test.ts
  • src/main/cursor/hook-service.ts
  • src/main/devin/hook-service.ts
  • src/main/droid/hook-service.ts
  • src/main/gemini/hook-service.ts
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/kimi/hook-service.ts

Comment thread src/main/kimi/hook-service.ts Resolved
The managed shell/cmd hook scripts sourced the endpoint file
(`. "$file"` / `call "%file%"`), so any shell/batch written into that
path executed with the agent's privileges. They also passed the hook
token and the raw payload as curl command-line arguments (readable by
other same-UID processes via `ps`/`/proc/<pid>/cmdline`) and did not
disable proxying for the loopback POST.

Add a shared builder (`agent-hooks/managed-hook-script.ts`) used by every
shell/cmd hook:

- Parse only the four known ORCA_AGENT_HOOK_* keys from the endpoint
  file; never execute it. Values are assigned as literals, so a command
  substitution in the file is stored, not run.
- Stream the token into curl as a header from stdin (`-H @-`) and read
  the payload from a private temp file (`--data-urlencode payload@<file>`),
  so neither appears on the command line.
- Add `--noproxy 127.0.0.1` so a configured http_proxy/ALL_PROXY cannot
  route the token and prompt off-box.
- Validate the port as digits-only; keep the Claude hook silent on stdout.

The JS, Python, and PowerShell hooks already parsed the file and sent the
token as an in-process header, so they are unchanged. On Windows cmd the
token stays on argv (no mktemp; stdin is taken by the payload) — a
documented, same-user-only exposure matching the already-ACL'd endpoint
file.

STA-1284

Co-authored-by: Orca <[email protected]>
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-1284-claude-hook-security-triage branch from 0c5da1f to 82ef739 Compare July 4, 2026 01:09

@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 (1)
src/main/agent-hooks/managed-hook-script.test.ts (1)

113-127: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

run() spawns a real process with no timeout/kill safeguard.

If a regression causes the script or curl to hang (e.g. blocked on stdin/network), this helper never kills the child; only Vitest's test-level timeout would eventually intervene, leaking an orphaned process per hung test run in CI. Capturing stderr would also help diagnose failures, since only stdout is currently collected.

🔧 Suggested hardening
   function run(env: Record<string, string>, payload: string): Promise<{ stdout: string }> {
     return new Promise((resolve, reject) => {
       const child = spawn('/bin/sh', [scriptPath], { env: { ...process.env, ...env } })
       let stdout = ''
+      let stderr = ''
+      const timer = setTimeout(() => {
+        child.kill('SIGKILL')
+        reject(new Error(`hook script timed out; stderr: ${stderr}`))
+      }, 5000)
       child.stdout.on('data', (c) => {
         stdout += String(c)
       })
+      child.stderr.on('data', (c) => {
+        stderr += String(c)
+      })
       child.on('error', reject)
-      child.on('close', () => resolve({ stdout }))
+      child.on('close', () => {
+        clearTimeout(timer)
+        resolve({ stdout })
+      })
       child.stdin.end(payload)
     })
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7a7a3e40-bd43-49eb-b006-af9c0d9fb680

📥 Commits

Reviewing files that changed from the base of the PR and between 0c5da1f17446ce23ddb52027bd7c883823f6313c and 82ef739.

📒 Files selected for processing (22)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/installer-utils.ts
  • src/main/agent-hooks/managed-hook-script.test.ts
  • src/main/agent-hooks/managed-hook-script.ts
  • src/main/agent-hooks/server.test.ts
  • src/main/antigravity/hook-service.test.ts
  • src/main/antigravity/hook-service.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/codex/hook-service.ts
  • src/main/command-code/command-code-managed-script.ts
  • src/main/copilot/hook-service.ts
  • src/main/cursor/hook-service.test.ts
  • src/main/cursor/hook-service.ts
  • src/main/devin/hook-service.test.ts
  • src/main/devin/hook-service.ts
  • src/main/droid/hook-service.ts
  • src/main/gemini/hook-service.ts
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/kimi/hook-service.test.ts
  • src/main/kimi/hook-service.ts
✅ Files skipped from review due to trivial changes (1)
  • config/tsconfig.cli.json
🚧 Files skipped from review as they are similar to previous changes (15)
  • src/main/agent-hooks/installer-utils.ts
  • src/main/grok/hook-service.test.ts
  • src/main/kimi/hook-service.ts
  • src/main/antigravity/hook-service.test.ts
  • src/main/cursor/hook-service.test.ts
  • src/main/gemini/hook-service.ts
  • src/main/agent-hooks/server.test.ts
  • src/main/codex/hook-service.ts
  • src/main/grok/hook-service.ts
  • src/main/cursor/hook-service.ts
  • src/main/command-code/command-code-managed-script.ts
  • src/main/copilot/hook-service.ts
  • src/main/antigravity/hook-service.ts
  • src/main/agent-hooks/managed-hook-script.ts
  • src/main/claude/hook-service.ts

… via curl

The first cut of this change moved the hook token off argv along with the
payload — first via `-H @-` (header from stdin), which curl <7.55 silently
drops (breaking agent statuses on 2013-2017-era SSH remotes), then via
`-K -` (config from stdin), which works on old curl but reads stdin as a curl
*config file*: a newline in the token could smuggle a `url =`/`output =`
directive, so it needed a UUID-charset guard to be safe.

That whole mechanism existed only to hide a per-session, loopback-only UUID
that a same-user process already reads from the 0600 endpoint file, and that
the Windows path already leaves on argv. The mitigation was out of proportion
to the asset. Send the token as a plain `-H` header on argv instead.

The security wins that matter are unchanged: the endpoint file is still parsed
never sourced (the code-exec fix), the payload — the prompt and tool output —
is still off argv in a private temp file, and `--noproxy 127.0.0.1` still
blocks loopback proxy exfil. The token's argv exposure is same-user only and
now matches the documented Windows behavior. The PR no longer changes any curl
version requirement.

Also adds service-level script-pinning tests for gemini/copilot/droid and
fixes two Windows-only test bugs (devin cmd assertions, kimi USERPROFILE).

STA-1284

Co-authored-by: Orca <[email protected]>

@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 (1)
src/main/agent-hooks/managed-hook-script.ts (1)

81-91: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Trim the design-rationale comment to align with the repo's comment-brevity rule.

This 11-line block explaining the token-stays-on-argv tradeoff is valuable context, but the coding guideline for this file type asks for non-obvious-behavior comments to stay to one or two lines. Consider condensing to the core "why" (loopback-only, already in 0600 endpoint file, moving off argv needs curl config-file injection surface) and moving the fuller design discussion to a linked doc (e.g., docs/design/agent-status-over-ssh.md, already referenced elsewhere in this codebase) if deeper justification is needed for auditors.

As per coding guidelines, "Keep comments short — one or two lines, capturing only the non-obvious reason."

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7d4ee845-f838-439f-a03d-f00a66f1cabf

📥 Commits

Reviewing files that changed from the base of the PR and between 82ef739 and 63b7faa.

📒 Files selected for processing (9)
  • src/main/agent-hooks/managed-hook-script.test.ts
  • src/main/agent-hooks/managed-hook-script.ts
  • src/main/claude/hook-service.test.ts
  • src/main/copilot/hook-service.test.ts
  • src/main/cursor/hook-service.test.ts
  • src/main/devin/hook-service.test.ts
  • src/main/droid/hook-service.test.ts
  • src/main/gemini/hook-service.test.ts
  • src/main/kimi/hook-service.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/cursor/hook-service.test.ts
  • src/main/claude/hook-service.test.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

The endpoint-file hardening still needs a fresh change against current main. This older script consolidation has been overtaken by changes to restart recovery and input handling, so it should be retired while that work remains tracked.

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.

1 participant