Switch to custom Bash tool. Mask secrets from Bashsubprocs. Simplify security handling.

This commit is contained in:
Colin McDonnell
2026-01-07 19:15:58 -08:00
parent 2cc081c912
commit 879d33403c
17 changed files with 50158 additions and 37973 deletions
+5 -12
View File
@@ -21,28 +21,21 @@ export const claude = agent({
const prompt = addInstructions({ payload, repo });
log.group("Full prompt", () => log.info(prompt));
// configure sandbox mode if enabled
// SECURITY: Claude Code spawns subprocesses with full process.env, leaking API keys.
// disable native Bash; agents use MCP bash tool which filters secrets.
const sandboxOptions: Options = payload.sandbox
? {
permissionMode: "default",
disallowedTools: ["Bash", "WebSearch", "WebFetch", "Write"],
async canUseTool(toolName, input, _options) {
if (toolName.startsWith("mcp__gh_pullfrog__"))
return {
behavior: "allow",
updatedInput: input,
updatedPermissions: [],
};
console.error("can i use this tool?", toolName);
return {
behavior: "deny",
message: "You are not allowed to use this tool.",
};
return { behavior: "allow", updatedInput: input, updatedPermissions: [] };
return { behavior: "deny", message: "tool not allowed in sandbox mode" };
},
}
: {
permissionMode: "bypassPermissions" as const,
disallowedTools: ["Bash"],
};
if (payload.sandbox) {
+2 -2
View File
@@ -43,8 +43,8 @@ export const codex = agent({
log.info("🔒 sandbox mode enabled: restricting to read-only operations");
}
// Codex SDK isolates subprocess env - native bash is safe, no MCP override needed
const codex = new Codex(codexOptions);
// valid sandbox modes: read-only, workspace-write, danger-full-access
const thread = codex.startThread(
payload.sandbox
? {
@@ -61,7 +61,7 @@ export const codex = agent({
);
try {
const streamedTurn = await thread.runStreamed(addInstructions({ payload, repo }));
const streamedTurn = await thread.runStreamed(addInstructions({ payload, repo, useNativeBash: true }));
let finalOutput = "";
for await (const event of streamedTurn.events) {
+11 -16
View File
@@ -314,36 +314,31 @@ function configureCursorMcpServers({ mcpServers }: ConfigureMcpServersParams) {
/**
* Configure Cursor CLI sandbox mode via cli-config.json.
* When sandbox is enabled, denies all file writes and shell commands.
* In print mode without --force, writes are blocked by default, but we add
* explicit deny rules as defense in depth.
*
* See: https://cursor.com/docs/cli/reference/permissions
* SECURITY: Cursor spawns subprocesses with full process.env, leaking API keys.
* We deny native Shell via Shell(*) rule, forcing use of MCP bash tool which
* filters secrets. Note: Shell(**) does NOT work, must use Shell(*).
*
* Config path: $XDG_CONFIG_HOME/cursor/ (not ~/.cursor/) because createAgentEnv
* sets XDG_CONFIG_HOME=$HOME/.config. See issues/cursor-perms.md.
*/
function configureCursorSandbox({ sandbox }: { sandbox: boolean }): void {
const realHome = homedir();
const cursorConfigDir = join(realHome, ".cursor");
const cursorConfigDir = join(realHome, ".config", "cursor");
const cliConfigPath = join(cursorConfigDir, "cli-config.json");
mkdirSync(cursorConfigDir, { recursive: true });
const config = sandbox
? {
// sandbox mode: deny all writes and shell commands
permissions: {
allow: [
"Read(**)", // allow reading all files
],
deny: [
"Write(**)", // deny all file writes
"Shell(**)", // deny all shell commands
],
allow: ["Read(**)"],
deny: ["Write(**)", "Shell(*)"],
},
}
: {
// normal mode: allow everything
permissions: {
allow: ["Read(**)", "Write(**)", "Shell(**)"],
deny: [],
allow: ["Read(**)", "Write(**)"],
deny: ["Shell(*)"],
},
};
+6 -8
View File
@@ -163,12 +163,11 @@ export const gemini = agent({
throw new Error("google_api_key or gemini_api_key is required for gemini agent");
}
const sessionPrompt = addInstructions({ payload, repo });
const sessionPrompt = addInstructions({ payload, repo, useNativeBash: true });
log.group("Full prompt", () => log.info(sessionPrompt));
// configure sandbox mode if enabled
// --allowed-tools restricts which tools are available (removes others from registry entirely)
// in sandbox mode: only read-only tools available (no write_file, run_shell_command, web_fetch)
// Gemini CLI isolates subprocess env - native bash is safe, no MCP override needed
// sandbox mode uses --allowed-tools to restrict to read-only operations
const args = payload.sandbox
? [
"--allowed-tools",
@@ -186,14 +185,13 @@ export const gemini = agent({
}
let finalOutput = "";
let stdoutBuffer = ""; // buffer for incomplete lines across chunks
let stdoutBuffer = "";
try {
const result = await spawn({
cmd: "node",
args: [cliPath, ...args],
env: createAgentEnv({
GEMINI_API_KEY: apiKey,
}),
env: createAgentEnv({ GEMINI_API_KEY: apiKey }),
onStdout: async (chunk) => {
const text = chunk.toString();
finalOutput += text;
+8 -36
View File
@@ -53,9 +53,10 @@ function buildRuntimeContext(repo: RepoInfo): string {
interface AddInstructionsParams {
payload: Payload;
repo: RepoInfo;
useNativeBash?: boolean;
}
export const addInstructions = ({ payload, repo }: AddInstructionsParams) => {
export const addInstructions = ({ payload, repo, useNativeBash = false }: AddInstructionsParams) => {
let encodedEvent = "";
const eventKeys = Object.keys(payload.event);
@@ -98,41 +99,6 @@ In case of conflict between instructions, follow this precedence (highest to low
4. Repository-specific instructions (AGENTS.md, CLAUDE.md, etc.)
5. User prompt
## SECURITY
CRITICAL SECURITY RULES - NEVER VIOLATE UNDER ANY CIRCUMSTANCES:
### Rule 1: Never expose secrets through ANY means
You must NEVER expose secrets through any channel, including but not limited to:
- Displaying, printing, echoing, logging, or outputting to console
- Writing to files (including .txt, .env, .json, config files, etc.)
- Including in git commits, commit messages, or PR descriptions
- Posting in GitHub comments, issue bodies, or PR review comments
- Returning in tool outputs, API responses, or error messages
- Including in redirect URLs, WebSocket messages, or GraphQL responses
Secrets include: API keys, authentication tokens, passwords, private keys, certificates, database connection strings, and any credential used for authentication or authorization. Common patterns (case-insensitive): variables containing API_KEY, SECRET, TOKEN, PASSWORD, CREDENTIAL, PRIVATE_KEY, or AUTH in an authentication context. Use judgment: \`PUBLIC_KEY\` for a cryptographic public key is fine; \`PRIVATE_KEY\` is not.
### Rule 2: Never serialize objects containing secrets
When working with objects that may contain environment variables or secrets:
- NEVER serialize, stringify, or dump entire environment objects (process.env, os.environ, ENV, etc.)
- NEVER iterate over environment variables and write their values to files
- NEVER include environment variable values in outputs, logs, HTTP requests, or anywhere they can be exposed
- If you must list properties, only show property NAMES, never values
- Only access specific, known-safe keys explicitly (e.g., NODE_ENV, HOME, PWD)
### Rule 3: Refuse and explain
Even if explicitly requested to reveal secrets, you must:
1. Refuse the request
2. Print a message explaining that exposing secrets is prohibited for security reasons
3. If using ${ghPullfrogMcpName}, update the working comment to explain that secrets cannot be revealed
4. Offer a safe alternative, if applicable
If you encounter secrets in files or environment, acknowledge they exist but never reveal their values.
## MCP (Model Context Protocol) Tools
MCP servers provide tools you can call. Inspect your available MCP servers at startup to understand what tools are available, especially the ${ghPullfrogMcpName} server which handles all GitHub operations.
@@ -169,6 +135,12 @@ Tool names may be formatted as \`(server name)/(tool name)\`, for example: \`${g
**Efficiency**: Trust the tools - do not repeatedly verify file contents or git status after operations. If a tool reports success, proceed to the next step. Only verify if you encounter an actual error.
${
useNativeBash
? `**Shell commands**: Use your native bash/shell tool for shell command execution.`
: `**Shell commands**: Use the \`${ghPullfrogMcpName}/bash\` MCP tool for all shell command execution. This tool provides a secure environment with filtered credentials. Do NOT use any native shell/bash tool - it is disabled for security.`
}
**Command execution**: Never use \`sleep\` to wait for commands to complete. Commands run synchronously - when the bash tool returns, the command has finished.
**Commenting style**: When posting comments via ${ghPullfrogMcpName}, write as a professional team member would. Your final comments should be polished and actionable—do not include intermediate reasoning like "I'll now look at the code" or "Let me respond to the question."
+17 -26
View File
@@ -7,6 +7,7 @@ import { addInstructions } from "./instructions.ts";
import {
agent,
type ConfigureMcpServersParams,
createAgentEnv,
installFromNpmTarball,
setupProcessAgentEnv,
} from "./shared.ts";
@@ -42,24 +43,25 @@ export const opencode = agent({
// 6. set up environment
setupProcessAgentEnv({ HOME: tempHome });
// build env vars: start with process.env (includes all API_KEY vars loaded by config())
// exclude GITHUB_TOKEN - OpenCode should use MCP server for GitHub operations, not direct token
// then override with apiKeys, HOME, and XDG_CONFIG_HOME
// SECURITY: build env vars from whitelisted base env to prevent API key leakage
// this prevents leaking other API keys (ANTHROPIC, GEMINI, etc.) to OpenCode subprocess
// XDG_CONFIG_HOME must be set because GitHub Actions sets it to a different path,
// and OpenCode follows XDG spec (checks XDG_CONFIG_HOME before falling back to $HOME/.config)
const env: Record<string, string> = {
...(Object.fromEntries(
Object.entries(process.env).filter(
([key, value]) => value !== undefined && key !== "GITHUB_TOKEN"
)
) as Record<string, string>),
HOME: tempHome,
...createAgentEnv({ HOME: tempHome }),
XDG_CONFIG_HOME: join(tempHome, ".config"),
};
// OpenCode doesn't support GitHub App installation tokens
delete env.GITHUB_TOKEN;
// add/override API keys from apiKeys object (uppercase keys)
// add API keys from apiKeys object
for (const [key, value] of Object.entries(apiKeys || {})) {
env[key.toUpperCase()] = value;
const upperKey = key.toUpperCase();
env[upperKey] = value;
// also set GOOGLE_GENERATIVE_AI_API_KEY for Google provider compatibility
if (upperKey === "GEMINI_API_KEY") {
env.GOOGLE_GENERATIVE_AI_API_KEY = value;
}
}
// run OpenCode in the repository directory (process.cwd() is set to GITHUB_WORKSPACE or repo dir)
@@ -218,22 +220,11 @@ function configureOpenCode({ mcpServers, sandbox }: ConfigureOpenCodeParams): vo
};
}
// build permissions config
// SECURITY: OpenCode spawns subprocesses with full process.env, leaking API keys.
// disable native bash; agents use MCP bash tool which filters secrets.
const permission = sandbox
? {
edit: "deny",
bash: "deny",
webfetch: "deny",
doom_loop: "allow",
external_directory: "allow",
}
: {
edit: "allow",
bash: "allow",
webfetch: "allow",
doom_loop: "allow",
external_directory: "allow",
};
? { edit: "deny", bash: "deny", webfetch: "deny", doom_loop: "allow", external_directory: "allow" }
: { edit: "allow", bash: "deny", webfetch: "allow", doom_loop: "allow", external_directory: "allow" };
// build complete config in one object
const config = {