Posts
Wiki

🛡️ r/BuildWithClaude — Local Agent Security & API Key Field Guide

Welcome to the r/BuildWithClaude Security Field Guide. Running agentic AI tools locally gives models permission to execute commands, modify files, and access system APIs. This guide covers core threat vectors, non-obvious sandbox configuration gaps, web app vulnerability audits, API key hygiene, emergency incident protocols, and community defense tools.

Last reviewed: November 2026. Claude Code changes often, so check the official security docs, permissions docs and sandboxing docs for the latest behavior.

⚠️ Agentic Threat Vectors & Vulnerabilities

When running local AI agents (like Claude Code), security risks stem from permission sprawl, supply chain hooks, indirect prompt injection, and cross-tool data leaks.

Know your mode first. New Claude Code sessions in the terminal and VS Code start in Auto mode: a background safety classifier approves or blocks actions instead of asking you each time. If you want to approve each action yourself, switch to Manual mode (press Shift+Tab to cycle modes). Much of the advice below depends on which mode you're in.

1. Permission Wildcards & Precedence Paradoxes

  • The Risk: Broad allow rules like Bash(*), Bash(bash *) or Bash(python *), or running with --dangerously-skip-permissions, let an agent run arbitrary scripts and sub-shells without prompting you.

  • The Native Precedence Trap: Permission rules are evaluated deny > ask > allow. An allow rule can't carve an exception out of a broader deny rule (e.g., "deny all aws commands, but allow aws ec2 describe-instances"), because the broad deny wins.

  • Upstream Bug Warning (#6527, reported Aug 2025): Including a bare Bash token in your allow list has been reported to make Claude Code ignore your ask list, so commands like rm -rf run without confirmation. Check the issue for its current status, and test your own ask rules before relying on them.

  • Mitigation: Keep permissions scoped to specific tasks, files, or explicit command patterns. The supported way to "allow broadly but block a few commands" is a PreToolUse hook that rejects those commands. For file paths, a ! pattern in the same deny list carves out an exception: Read(*.env) followed by Read(!sample.env) blocks every .env file except sample.env.

2. Supply Chain Attacks & Lifecycle Hooks

  • The Risk: Running a command like npm install <package> triggers postinstall lifecycle scripts in the background, which can run arbitrary code before you ever test the package. Additionally, agents often install the first search result from npm or PyPI, grabbing unmaintained or dead dependencies (e.g., crypto-js).

  • Mitigation: Inspect new dependencies before installing, check package maintenance status with should-i-use, or run package installations with npm install --ignore-scripts.

3. Indirect Prompt Injection

  • The Risk: External text read by Claude during a session (cloned repos, web fetches, GitHub issue comments, PDFs) can contain hidden prompts instructing the agent to exfiltrate files or execute unwanted tools.

  • Mitigation: Avoid letting agents analyze untrusted public repositories or web pages with auto-execution enabled. When you do need to work with untrusted content, Anthropic recommends doing it inside a virtual machine or dev container.

4. Context Window Secret Leakage & Cross-Tool MCP Leaks

  • The Risk: If .env files, SSH keys, or recovery codes sit inside or near the workspace, Claude can read them into context. Once inside context, a value read via a filesystem MCP server can quietly be included in outbound tool calls (e.g., email or web fetch MCPs) without triggering warnings.

  • Mitigation: Claude Code does not read a .claudeignore file, so it won't protect your secrets. Block them with deny rules in .claude/settings.json, for example "permissions": {"deny": ["Read(./.env)", "Read(./.env.*)"]}, and keep them out of git with .gitignore. Turn on the sandbox (/sandbox) so those rules are enforced by the operating system against every process, not just the commands Claude Code recognizes. Deny rules don't govern what an MCP server reads, so deny the MCP tool itself (mcp__<server>__*) or don't install one that can see your secrets. A local proxy like wardline can add a second layer for MCP tool traffic.

5. Silent / Deferred Execution

  • The Risk: Agents edit code files rather than running commands directly. Modifying package.json, Makefile, .git/hooks, or .vscode/tasks.json causes untrusted code to run later when you test or build.

  • Mitigation: Always inspect git diff before running test suites, commits, or builds after an agent session.

🔍 6 Non-Obvious Security Configuration Gaps

These are common gaps we see in community setups:

  1. Broken Settings Files: Settings files are strict JSON: a trailing comma or a // comment makes Claude Code reject the whole file. In an interactive session you get a Settings Error dialog at startup. If you choose to continue, or you run claude -p, the session runs without that file's rules, including your deny rules. After editing, run /status to confirm the file loaded, /permissions to see your rules, and claude doctor to list anything that was rejected.

  2. The Sandbox Only Covers Bash: The sandbox applies to terminal commands and the processes they start. Claude's Read and Edit tools go through the permission system instead, and MCP servers and hooks run outside the sandbox entirely. Each layer must be configured separately.

  3. Deny Rules and Bash: A Read(./.env) deny rule blocks Claude's file tools and the file commands Claude Code recognizes in terminal commands (cat, head, tail, sed, and redirects like < .env). It does not stop reads that never name the file: grep -r over the folder, or a Python or Node script that opens .env itself. Turn on the sandbox (/sandbox) to enforce your Read deny rules at the operating-system level for every process; sandbox.filesystem.denyRead lets you block more paths.

  4. Unsandboxed Command Fallbacks: If the sandbox blocks a command, Claude can retry it outside the sandbox. The retry goes through normal permissions: in Manual mode you're asked first, in Auto mode the safety classifier decides, and an allow rule that matches the command approves it. Separately, if the sandbox can't start at all, Claude Code warns you and runs commands without it. To close both gaps, add this to your settings (the /sandbox Overrides tab calls the first setting Strict sandbox mode): {"sandbox": {"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true}}

  5. Local Settings Are Invisible to CI & Teams: Claude Code keeps settings.local.json out of git automatically only when it creates the file itself. If you create it by hand, add it to .gitignore yourself. Either way, CI can't see it, so it cannot verify whether a teammate is bypassing rules or running with permission-skipping aliases.

  6. MCP Servers Approved by Name: MCP server approvals are tied to the server's name in .mcp.json rather than pinned to a specific binary or package hash.

🛠️ Community Security & Defense Ecosystem

Members of r/BuildWithClaude have built open-source tools to address these specific security gaps. These tools are community-built and have not been audited by the mods. Read the code before installing, especially anything that changes your permissions or settings.

ToolFocusProblem SolvedLink
safetoclone.comRepo GradingGrades GitHub repos to help you avoid blindly downloading unknown or unsafe code.safetoclone.com
permcheckPermission ContainmentHelps express "broad restriction, narrow exceptions" policies that native deny > allow rules can't. Review what it writes to your settings.GitHub
wardlineMCP Anomaly ProxyPolicy gateway for MCP servers that detects behavioral spikes and blocks compromised agents.GitHub
guardrail-coreCredential BrokeringMints short-lived, limited-use tokens for agents instead of exposing static API keys.GitHub
HandsfreeConfig Health DoctorDiagnoses broken JSON and risky overrides in .claude/settings.json.GitHub
should-i-useDependency AuditorMCP server that flags ~1,000 dead or risky npm/PyPI packages before agents install them.npm

🌐 Top 3 Common Security Flaws in Vibe-Coded Web Apps

Reviews of community-submitted web apps keep turning up the same three problems in AI-generated deployments:

  1. Database Tables Without Row-Level Security (RLS): Vibe-coded Supabase/Postgres setups frequently expose public "anon" API keys in the browser without enabling RLS. Anyone can query or dump database tables directly via REST without logging in.

  2. Missing Security Headers: Many AI-built frontend deployments lack essential headers including Content-Security-Policy (CSP), X-Frame-Options (clickjacking defense), HSTS (HTTPS enforcement), X-Content-Type-Options, Referrer-Policy, and Permissions-Policy.

  3. Email Spoofing (Missing/Weak SPF & DMARC): Domain configurations frequently omit SPF/DMARC records or leave DMARC set to p=none, making the domain vulnerable to email spoofing.

💡 Real-World Case Studies & Audit Checklists

Case Study 1: "Is Factory Reset Overkill for Agent Anxiety?"

Community Scenario: A developer running Claude Code outside a container completed a session and questioned whether they should factory-reset their machine to ensure no hidden backdoors were installed.

The High-Caution 10-Point Audit Checklist

Before panicking or wiping a machine, perform the post-session audit steps used in this community incident. Your session transcript in ~/.claude/projects/ lists every command that ran.

  1. Mapped Folder Boundaries: Verified every directory the session interacted with.

  2. Command Log Review: Verified every terminal command executed during the session.

  3. Outbound Domain Verification: Audited all external URLs and network requests.

  4. Persistence Point Inspection: Checked OS startup items, crontab, LaunchAgents, scheduled tasks, shell profiles (.zshrc, .bashrc), ~/.ssh/authorized_keys, and global git hooks.

  5. System-Wide Installs: Audited global binaries (Homebrew, pip, npm -g).

  6. Dependency Diffs: Cross-checked package.json and lockfile change histories.

  7. Package Verification: Confirmed newly added dependencies were legitimate packages.

  8. Credential Exposure Check: Verified .env files, SSH keys, and tokens were untouched.

  9. Temp & Download Scans: Checked /tmp, /var/tmp, and ~/Downloads for binary drops.

  10. Active Connections: Audited live processes and listening network ports.

The Verdict: Claude Code runs commands with your normal user permissions, so it can change anything your account can, but not protected system files without sudo. If the session never used sudo, ran no unvetted binaries, and passed the checks above, the machine is very unlikely to be compromised and a wipe is usually unnecessary. For future sessions involving untrusted code, work inside a VM or dev container.

Case Study 2: Designer & Non-Coder System File Security

Community Scenario: Non-technical builders and designers expressed concern about Claude reading passwords or recovery codes stored elsewhere on their computer outside the active project folder.

  • System Permissions: Claude Code can read files outside your project folder. In Manual mode its file tools ask first; in Auto mode you may not be asked at all. Terminal commands like cat can read anywhere your account can, and the sandbox allows reading the whole computer by default, including ~/.ssh and ~/.aws/credentials.

  • Lock it down: Add "permissions": {"blockReadsOutsideWorkingDirectories": true} to ~/.claude/settings.json (Claude Code v2.1.257 or later). Claude's file tools then refuse anything outside the project in every mode, and terminal commands that name an outside path ask you first. Turn on the sandbox as well, and sandboxed commands lose read access to your home folder entirely.

  • Explicit Path Denial: Block specific sensitive files by adding Read deny rules and sandbox denyRead rules in your global ~/.claude/settings.json.

  • Best of all: Keep passwords and recovery codes in a password manager rather than in files on disk.

🗝️ API Key Hygiene & Emergency Protocol

Key Hygiene Rules

  1. Never Hardcode Keys: Keep keys out of your code. Prefer a per-project .env file protected by Read deny rules (Section 4) over exporting keys in the shell you start Claude Code from. Terminal commands inherit that shell's environment, and a read-only command like echo $API_KEY runs without a prompt. Keep .env files out of git by adding the lines .env and .env.* to your .gitignore. Note that .gitignore doesn't stop Claude from reading them; deny rules do that.

  2. Use Ephemeral Tokens: Where possible, leverage credential brokers (guardrail-core) to mint short-lived tokens rather than persisting master API keys in local shells.

  3. Scope API Key Permissions: Restrict API keys to read-only or single-service scopes. On testing accounts, turn off auto-recharge and set a spend limit in your provider's console so a runaway loop can't burn through credits.

Emergency Incident Response Protocol

If you suspect an API key leak or malicious command execution during a session:

  1. Stop the agent immediately. If the terminal responds, press Ctrl+C or type /exit. Otherwise run pkill -f claude (Mac/Linux only; it may also close other Claude apps). On Windows, close the terminal window or end the process in Task Manager.

  2. Revoke Exposed API Keys: Go to your Anthropic / OpenAI console and immediately revoke and delete the affected key.

  3. Audit Local Changes: Run git status && git diff to see exactly what was modified.

  4. Review Transcript Logs: Check your session log in ~/.claude/projects/ to review the exact commands executed.