Repository navigation
fix(core): prevent indirect prompt injection via build file modifications and untrusted flags - #29250
Conversation
…ions and untrusted flags
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
|
📊 PR Size: size/XL
|
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a robust security layer to mitigate indirect prompt injection attacks by tracking untrusted context and enforcing strict confirmation requirements for build-related operations. It adds mechanisms to detect untrusted shell flags and mandates user approval when modifying or executing build configuration files, significantly hardening the workspace against unauthorized modifications and command execution. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces build file protection and untrusted context tracking to prevent unauthorized build modifications and command execution with untrusted flags. The reviewer provided critical feedback highlighting several security and architectural vulnerabilities: naive whitespace splitting and command parsing in findUntrustedFlags and isBuildOrTestCommand can be bypassed with quotes or prefixed environment variables; the policy engine's build file protection can be bypassed via MCP filesystem tools; and tracking modified build files using a module-level global Set violates repository rules against global state, risking race conditions in concurrent environments. The reviewer recommended using shell-quote and getCommandRoots for robust command parsing, expanding tool name matching to cover MCP tools, adopting a session-scoped WeakMap for tracking modified files, and suppressing persistent approval options in the UI when modified build files are detected.
Note: Security Review did not run due to the size of the PR.
…d configuration security
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces robust build file protection and untrusted command flag detection to enhance execution security. It adds utilities to identify build files and track untrusted context, ensuring that modifications to build configuration files or execution of commands with untrusted flags always require explicit user confirmation (downgrading to ASK_USER or DENY in non-interactive mode) and suppress persistent approvals. Additionally, it updates the CLI UI to display critical security warnings and prevent truncation of build file diffs. A high-severity issue was identified in packages/core/src/tools/shell.ts where getModifiedBuildFiles() is called without passing the session key (this.context.config), which would cause it to default to the global session key and fail to retrieve modified build files recorded with the active configuration.
Note: Security Review did not run due to the size of the PR.
|
/gemini review |
1 similar comment
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces robust build file protection and untrusted command flag detection mechanisms to prevent malicious code execution. It adds utilities to identify build files and track untrusted context, updates the policy engine to require user confirmation for build file modifications, and enhances the CLI confirmation UI with critical security warnings. The review identified two critical issues: first, getModifiedBuildFiles in the shell tool is called without the session key, causing it to return an empty array and bypass the build file caution warning; second, applyShellHeuristics in the policy engine is missing the shellDirPath argument, which bypasses workspace boundary checks.
Note: Security Review did not run due to the size of the PR.
There was a problem hiding this comment.
Code Review
This pull request introduces robust security features, including Build File Protection and Untrusted Command Flags Detection, to prevent unauthorized modifications to build configurations and execution of untrusted commands. It adds utilities to identify build files and track untrusted context, updates the policy engine to require user confirmation for build file edits, and enhances the CLI to display critical security warnings and suppress persistent approvals. Feedback on the changes highlights a critical bug in shell.ts where getModifiedBuildFiles() is called without the session key, bypassing the caution warning, and a missing dependency (availableTerminalHeight) in a useCallback hook within ToolConfirmationMessage.tsx.
Note: Security Review did not run due to the size of the PR.
… ESLint errors in tracker
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a robust Build File Protection mechanism and untrusted command flag detection to enhance CLI security. It ensures that modifications to build configuration files (such as Bazel BUILD, package.json, and Makefiles) always require explicit user confirmation, even in automated or YOLO modes. It also tracks build files modified during a session to warn users before executing subsequent build commands, and detects untrusted command flags sourced from external contexts. The review feedback identifies a critical security vulnerability where redirection targets (e.g., shell output redirection) are ignored during token extraction, which could allow arbitrary file writes to bypass detection. Additionally, it is recommended to replace the module-level global regular expression with String.prototype.matchAll() to prevent state leakage and potential race conditions.
Note: Security Review did not run due to the size of the PR.
…matchAll to avoid mutating global RegExp
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces Build File Protection and Untrusted Command Flags Detection to prevent unauthorized build configuration modifications and execution of untrusted command arguments. It adds utilities to identify build files, track untrusted conversation context, and warn users during tool execution. The review feedback highlights critical security bypasses on Windows platforms (due to path normalization issues and backslash escaping in shell parsing) and recommends avoiding module-level global state in the tracker to prevent cross-session data leakage in concurrent environments.
… and mandatory session scoping
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces robust security protections for build file modifications and untrusted command flags. It adds policy checks to downgrade build file modifications to user confirmation, tracks modified build files and untrusted flags across the session, and updates the CLI to display critical security warnings and suppress persistent approvals when these risks are detected. Additionally, it disables truncation in the diff renderer for build files to ensure complete visibility. A critical security issue was identified in ShellToolInvocation.getConfirmationDetails where early returns for additional permissions (sandbox expansion) can bypass the newly introduced security checks for untrusted flags and modified build files.
Note: Security Review did not run due to the size of the PR.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a robust "Build File Protection" mechanism and untrusted command flag detection to enhance security. It ensures that modifications to build configuration files (such as Bazel BUILD, package.json, Makefile, etc.) or execution of shell commands containing untrusted flags require explicit user confirmation and suppress persistent approvals. Additionally, build file diffs are displayed without truncation in the UI. Feedback on the changes points out a potential security bypass on POSIX platforms due to a mismatch in backslash normalization between shell commands and untrusted texts, and suggests normalizing backslashes to forward slashes before performing substring checks.
Note: Security Review did not run due to the size of the PR.
66d3cb2 to
3bcd206
Compare
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces robust security features to protect against unauthorized build file modifications and untrusted command flag execution. It adds utilities to identify build configuration files, updates the PolicyEngine to downgrade modifications of these files to require explicit user confirmation, and tracks modified build files to warn users before executing subsequent build or test commands. Additionally, it detects and warns against executing shell commands containing flags sourced from untrusted conversation history. Feedback on these changes suggests enhancing the untrusted token indexing by splitting on slashes to capture individual path segments and filenames, and improving security warning clarity by capturing both the flag and its untrusted argument when a match is detected.
3bcd206 to
9f9e627
Compare
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements security enhancements by introducing Build File Protection and Untrusted Flag Detection. It adds utilities to identify build files and track modifications during a session, updates the PolicyEngine to require user confirmation for build file edits and commands using untrusted flags, and improves the UI to display relevant security warnings. Additionally, it introduces a disableTruncation feature for build file diffs to ensure full visibility of changes. I have no feedback to provide.
bfb71fd
# Multi-harness: Gemini CLI and Qwen Code harnesses Adds two run engines, both marked **beta**: `worca --engine gemini` (Google's Gemini CLI) and `worca --engine qwen` (Qwen Code). Qwen Code is a fork of Gemini CLI, so both run on one shared base, and each per-engine file keeps only what really differs. Unlike Cursor (#606), both adapters were **spiked against the real binaries** (gemini 0.63.0, qwen 0.25.0). The captured streams, and every fact the adapters rely on, are in `test/fixtures/gemini/README.md` and `test/fixtures/qwen/README.md`. ## Usage ```bash npm i -g @google/gemini-cli # GEMINI_API_KEY in worca's env (or ~/.gemini/.env), or sign in once with `gemini` npm i -g @qwen-code/qwen-code # choose an auth type once with `qwen`, or set a whole provider's env worca --project . --prompt "…" --engine gemini [--model gemini-3.8-flash] [--allow-unguarded-engine] ``` `WORCA_GEMINI_BIN` / `WORCA_QWEN_BIN` point worca at another binary. Both engines are also offered on New pipeline, as a default engine in Settings › Models, and in a project's Settings. ## Layout - `src/core/engines/gemini-family.mjs` holds the shared parts: - sessions named up front (`--session-id`) and resumed (`--resume`), with one fresh retry when the CLI no longer knows the session - prompt on stdin - workspace folders (`--include-directories`), refused inside Worca's home as for Copilot - `--allowed-mcp-server-names`, so only the run's servers attach - MCP server shape, `${VAR}` refs kept - Claude tool names - error classes, preflight, the turn cap and the spawn runner - `src/core/engines/gemini.mjs`: Gemini's own stream normalizer, its policy TOML and the checkout `.gemini/settings.json`. - `src/core/engines/qwen.mjs`: Qwen's stream is Claude-shaped, so it goes through the existing `claude-events.mjs` normalizer after a small rewrite: the session id gets its prefix, tool names become Claude's, and the `tool_call` meta tool is unwrapped. Rules and MCP servers go into a system settings file. - `src/core/engines/project-files.mjs`: Cursor's checkout-file writer and ownership ledger, moved out of `cursor.mjs` and given an engine parameter. The harness now handles any engine's checkout files: register, teardown, commit and diff. ## Capabilities (from the spike) | | Gemini CLI | Qwen Code | |---|---|---| | resume, stream events, MCP tools, permission rules | yes | yes | | system-prompt flag | **no**: `GEMINI_SYSTEM_MD` replaces the whole built-in prompt, so the prompt is folded in | **yes**: `--append-system-prompt`; a prompt too long for argv is folded into stdin | | cost | **no**: tokens only, shown as *cost unknown* | **no**: tokens only | | allowed tools, effort, sub-agents, hook telemetry, skills, sub-agent system prompt, turn budget | no | no (`--max-session-turns` did not cap tool calls in the spike) | ## Guardrails | Rule | Gemini CLI (`--admin-policy` TOML, admin tier) | Qwen Code (Claude syntax, as written) | |---|---|---| | bare `Bash`, `WebFetch`, `WebSearch`, MCP server or tool | held | held | | `Bash(git push:*)` | **partial**: prefix match; the spike showed `env git log` passes | **partial**: same gap | | `Read(…)` | **partial**: argsPattern on the file tools; the shell is not covered | held (a Read rule also stopped `cat` in the spike) | | `Edit(…)`, `Write(…)`, `NotebookEdit(…)` | **partial**: same | **partial**: the file tools stop, but the YOLO shell still writes the path | | unknown tools | unenforced | unenforced | - **Gemini ignores a policy file it cannot parse.** It only prints "Policy file error" on stderr and runs with no rule. The adapter stops the child on that line (a new `onStderrLine` hook in `superviseSpawn`). - **Qwen's env under scrub:** with a scrubbing set, Qwen gets `QWEN_` names plus only the provider it is set to (its chosen sign-in, else the provider its env names): `OPENAI_`/`DASHSCOPE_`, `GEMINI_`, `GOOGLE_` or `ANTHROPIC_`. worca's own keys for other providers stay out of its shell. - An `--admin-policy` file is also skipped when the system policy folder holds `.toml` files, so the run refuses then. ## Checkout files and MCP - **Gemini** reads MCP servers only from settings files, and its system-settings path must be owned by root. So worca writes the checkout's `.gemini/settings.json`, with the same ownership, exclude-line and teardown handling as Cursor's files. A tracked `.gemini/settings.json` makes a run with MCP servers refuse. - Gemini needs `GEMINI_CLI_TRUST_WORKSPACE=true`: without it a headless run exits 55, and `--skip-trust` drops the checkout's MCP servers. - **Qwen** honours `QWEN_CODE_SYSTEM_SETTINGS_PATH` for any owner. worca writes its servers and deny rules there, in its temp folder, merged over the machine's own system settings. Nothing goes into the checkout. (`--mcp-config` does not fill `${VAR}`, so it is not used.) ## Elsewhere - **Helper jobs** (titles, overview, PR description, Auto classifier, night decider) run on Claude, as on Cursor. The new `SIGN_IN_ENGINES` (cursor, gemini, qwen) replaces the `engine === 'cursor'` checks for: - model fields: no env, no upstream, no effort - helper routing - the Test button's scratch cwd and signed-out hint - Ask proposals and the models editor - **Read-only spawns and Ask refuse** on both engines. Both CLIs have an `--approval-mode plan`, but no lockdown was verified, so read-only jobs and Ask stay on Claude. - **Models:** worca ships none. Users add catalog models with Engine Gemini CLI or Qwen Code. - **UI:** engine picker buttons with the Beta badge, Settings engine cards, the models editor (connection text, no effort or pricing), and the usage-limit resume offers. - **Docs:** a new "Gemini CLI and Qwen Code" section in `docs/models.md`. ## Tests - New test files: - `test/gemini-adapter.test.mjs` and `test/qwen-adapter.test.mjs`: the normalizers against the real captures, argv, the rule plans, preflight, and the spawn paths with fake binaries (`test/helpers/fake-gemini-family.mjs`) - `test/gemini-qwen-helpers.test.mjs` - Extended: registry, beta, readiness, switch, catalog, manifest, policy, cascade, gate (`.gemini/settings.json` teardown and commit), picker, settings and models-view tests. ```bash node tools/test.mjs test/gemini-adapter.test.mjs test/qwen-adapter.test.mjs test/gemini-qwen-helpers.test.mjs ``` **Status: draft.** **End-to-end runs.** Real worca pipelines (`--yes`, default workflow, Permissive set) ran on both real CLIs, with a scratch `HOME` and `WORCA_HOME` and a small task: add `add(a, b)` to `math.mjs` with a `node:test` test. - **Gemini CLI** (`gemini-3.8-flash` via `auto`): two runs. Both completed all 7 executions, the reviewer passed, and the result was committed on the run branch; the summary says *cost unknown*. - **Qwen Code** (signed in through Gemini: `GEMINI_API_KEY` + `GEMINI_MODEL`): one run. It completed the same way; the summary says *cost unknown*. - **Rerun on the rebased commit (2026-10-20):** gemini 0.64.0 and qwen 0.25.3 (the current stable releases), with the Normal set and `--allow-unguarded-engine`, the same task, and a scratch `HOME` and `WORCA_HOME`. - **Gemini CLI** (model `auto`): 7 executions in 5m35s. Refine and the reviewer were clean, the result was committed, and `npm test` passes on it (2/2). No "denied by policy" this time. - **Qwen Code** (`GEMINI_API_KEY` + `GEMINI_MODEL=gemini-3.8-flash`): 7 executions in 4m03s. Same outcome, `npm test` 8/8. - The only tool errors were reads of files that did not exist yet, and one `npm test` run before the test file was written. - The first Gemini run found three bugs, now fixed: - The implementer could not read its plan: Gemini's file tools read only the workspace, and plans live in worca's store. Each store folder now brings its project's store folder into the workspace. - Gemini passes cwd-relative paths, so the run log showed them under worca's own directory. Tool paths are now made absolute against the spawn's cwd. - The CLI's step lines printed `$0.00` on engines that report no cost. This affected Copilot and Cursor too. They now show no cost, matching the run total. - **Known Gemini behaviour:** inside worca runs, Gemini now and then answers a plain `node --test math.test.mjs` with "Tool execution denied by policy". - worca passed no policy file on those runs (the spawn argv was checked). - The same command ran fine outside worca, and the agent recovered every time (it re-ran the test as `./math.test.mjs`). - **Likely cause:** a taint check in Gemini CLI itself, added in 0.63 ([#29250](google-gemini/gemini-cli#29250)). In a non-interactive run it turns an allowed shell call into a deny, with no rule named, in two cases: - a flag or path in the command appeared earlier in tool output (shell, MCP or web output). For example, `--test` printed by `cat package.json` taints a later `node --test`. - the session edited a build file and then runs a build or test command (npm, npx, make, pytest and others). - It runs before YOLO and has no setting to turn it off. 0.64 ([#29672](google-gemini/gemini-cli#29672)) narrows it, but `--test` is not on its safe list. Two open Gemini PRs (#29833, #29719) would narrow it further. - worca cannot switch it off, so it is left as a known limitation. **Tests.** - Full suite: 9,050 tests, 15 failures on the first run. - 9 were tests that pin the engine lists and the resume offers. They now include Gemini CLI and Qwen Code. - 4 were perf/timing tests that failed under the parallel run's load. They pass when run alone. - `wsmap-deps` fails locally only because this worktree has no `node_modules`. CI installs them. - My real `~/.worca-cc/settings.json` was unchanged before and after. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
This PR implements robust mechanisms to improve workspace boundary validation (specifically focusing on build configuration files and external command parameters) under restricted workspace mode. It refactors built-in execution paths (including
shell,edit, andwrite_file) to check for command flags or arguments guided by external context tags (such as Google Docs, web fetch, or MCP server responses) and require explicit user confirmation.Details
<untrusted_context>blocks, and verify whether a command contains parameters guided by external input.package.json,Makefile,pyproject.toml,BUILD.bazel) when edited or created. If build configuration changes are detected within the current session, any subsequent build or test command execution (such asnpm run,make,cargo,blaze) is surfaced for explicit user confirmation.ToolConfirmationMessageto display detailed context to the user, highlighting specific parameters or recent build modifications, and explaining the execution options.Related Issues
Related to FixBug-cla-445881265
How to Validate
npm test -w @google/gemini-cli
Pre-Merge Checklist