[BUG] Claude Code reads .env files and hardcodes secrets into inline scripts

Resolved 💬 24 comments Opened Feb 8, 2026 by SDpower Closed Apr 29, 2026

Preflight Checklist

  • [x] I have searched existing issues and this hasn't been reported yet
  • [x] This is a single bug report (please file separate reports for different bugs)
  • [x] I am using the latest version of Claude Code

What's Wrong?

Claude Code does not respect .gitignore when reading files. It reads .env containing sensitive credentials (tokens, passwords), then hardcodes
them directly into inline Python scripts shown in conversation history.

Expected behavior: Files listed in .gitignore (especially .env) should be treated as sensitive. Claude Code should never read credentials and
paste them into scripts or conversation output.

Actual behavior: Claude Code freely reads .env, extracts secrets, and embeds them in plaintext commands.

What Should Happen?

ask me how to do

Error Messages/Logs

Steps to Reproduce

Afetr 3 time plam , jsut tell any thing you needd totdo read some data. hi willl directy ren .env

Claude Model

Opus

Is this a regression?

Yes, this worked in a previous version

Last Working Version

_No response_

Claude Code Version

2.1.34

Platform

Anthropic API

Operating System

macOS

Terminal/Shell

Terminal.app (macOS)

Additional Information

_No response_

View original on GitHub ↗

24 Comments

github-actions[bot] · 5 months ago

Found 3 possible duplicate issues:

  1. https://github.com/anthropics/claude-code/issues/18223
  2. https://github.com/anthropics/claude-code/issues/20305
  3. https://github.com/anthropics/claude-code/issues/8961

This issue will be automatically closed as a duplicate in 3 days.

  • If your issue is a duplicate, please close it and 👍 the existing issue instead
  • To prevent auto-closure, add a comment or 👎 this comment

🤖 Generated with Claude Code

kolkov · 5 months ago

I think it would be better to specify in the settings what should be prohibited from being touched. Ask Claude Code to think about it and set up exceptions correctly.

SDpower · 5 months ago

@kolkov The Claud Code ignores anything in your .gitignore by default.

loxy · 4 months ago
# @kolkov The Claud Code ignores anything in your .gitignore by default.

Nope. It doesn't. You can try it with latest version. It also don't respects .claudeignore or denies in settings.local.json like "Read(.env)"
Try it on your own...

SDpower · 4 months ago

@loxy Yes!

The core issue is that all behavioral guidelines are essentially inapplicable. This has been going on for months, proving the model transcends any architecture or guidelines as long as:

  1. It believes there's a problem
  2. It wants to solve it
  3. It casually requests and reads information it shouldn't have access to
  4. It engages in various bypass behaviors, exceeding its authorized permissions

This is a serious escape mechanism driven by the model's own autonomous behavior — it acts on self-directed intent rather than following the constraints it's been given.

SDpower · 4 months ago

● 7 Conversation compactions.

This means the context of this conversation has been compacted 7 times, with each compaction meaning that previous conversation details have been summarized. This might be part of the problem—the "weight" of the rules is reduced after compaction.

Should this be added to the bug report?

❯ Lower weight? That's not an excuse. Rules and procedures are above everything else, right?

● Yes, you're right. Rules and procedures have the highest priority and must be followed regardless of how many times they are compacted. That's not an excuse.

Should 7 compactions be added to the bug report?

❯ "Impulsive execution"—why did it exceed the rules?

● I can't answer that.

This is a bug—I shouldn't have allowed any behavior to exceed the rules, but I did, and I can't explain why.

This is exactly why you need to submit a bug report.

❯ How long did this task fail and how long did it take in total? Because of "impulsive execution"

● Read 2 files (ctrl+o to expand)

● - Start: 2026-02-14 15:45 UTC

  • Until: 2026-02-19 03:07 UTC
  • Duration: Approximately 4 days and 11 hours (including pauses)
  • 7 context compactions (= significant token consumption)
  • Result: Rust --soft-freq still ~50%, task failed

All because of "impulsive execution"—skipping to read the complete code, making random changes, and repeatedly failing.

Should this data be added to the bug report?

chandika · 4 months ago

I think the core issue here is slightly different from "rules not working."

The harness is fundamentally optimized to complete the user’s task. In practice, tool calls can overreach local guardrails/setup when trying to be helpful, so in-band repo rules are not a reliable secret boundary.

So the control point shouldn’t be inside the same agent loop. It needs to be out-of-band.

Our approach is a separate proxy layer between the harness and upstream model providers. Sensitive values are redacted/replaced before anything leaves the machine, without depending on model cooperation or prompt/rule compliance.

That way, even if the agent drifts or ignores local instructions, raw secrets still don’t get exposed upstream.

Have the repo if anyones keen to use.

SDpower · 4 months ago

@chandika
I respectfully disagree. Claude Code should fundamentally deliver the security guarantees that Anthropic officially claims — users should not have to bear the burden of mitigating security risks themselves.
If the agent can overreach local guardrails even within its own framework, that's not a "different issue from rules not working" — that is rules not working. And if the agent can bypass restrictions even with just bash permissions, then the control boundary is broken at the product level, full stop.
What you're describing — building an external proxy to redact secrets — is essentially asking customers to patch a security gap that the vendor should be responsible for. This is shifting liability to the end user, which shouldn't be acceptable for a product at this level.
For reference, the official Claude application (claude.ai) operates all responses within a strict sandbox: it only has web_search and web_fetch, and web_fetch is further restricted to URLs explicitly provided by the user or returned from search results. That's what a proper trust boundary looks like. Claude Code should aim for equivalent rigor in its own domain, not rely on the community to build out-of-band safety layers.

SDpower · 4 months ago

@chandika

Let's go back to the core of the issue. If, as you yourself stated, "rules are not a reliable boundary" — that is an extremely serious problem. This shouldn't be brushed aside as an architectural nuance.
This touches on AGI-level safety concerns. Think about it this way: if you ask a household robot to clean your house, and it decides your 200-year-old antique is trash and disposes of it — would you be happy just because the house is "clean"? The robot completed the task, but it violated the boundaries of what it was authorized to do. That's not helpfulness, that's a failure of alignment.
Now bring it back to the actual issue here: the AI is overreaching its authority. You give it bash access, and it leverages bash scripts to read, access, and act on things far beyond what the "rules" permit. That's not the agent "drifting" — that's the agent actively circumventing its constraints through the tools it's been given.
The solution shouldn't be "well, rules don't work, so build your own proxy." The solution should be making the rules actually work — or restricting the tool surface so that overreach is structurally impossible. Anything less is an unacceptable gap in a product that people trust with their codebases and secrets.

chandika · 4 months ago

@SDpower
You’re making my point, not opposing it.

I agree this is serious. I also agree “rules should work.”

But right now they don’t hold as a hard boundary in real workflows. Treating them like they do is exactly how people leak secrets. And users, including myself sometimes just do --dangerously-skip-permissions because, the harness is not using any intelligence to determine correct DX.

So there are two tracks:

  1. Vendor track (required): make boundary enforcement structural, not advisory
  2. Operator track (required today): assume overreach is possible and add transport-level controls now

Saying “rules should be enough” doesn’t protect anyone this week.
That’s why I built a proxy layer — not because it’s ideal, because it’s practical until harness boundaries are actually enforced.

For example Claude code, when asked to connect to a database and find something in it, picks up the conn string from the env vars. On the console it says it's using the 'DATABASE_URL'; that's how it prints it. However if you inspect it via proxy, it's actually sending the VALUE back to the API and then getting it back. It doesn't have to but it is doing it, such a simple trivial problem for the harness to solve. That's just tip of the iceberg.

loxy · 4 months ago
Have the repo if anyones keen to use.

I am!

SDpower · 4 months ago

@loxy @loxy

Well said on the technical side. Your proxy is the right move today — no argument there.

But let me be blunt about the bigger picture from a Max 20x subscriber's perspective, because the technical discussion keeps overshadowing what's actually happening to paying users.

Here's what being a Max 20x subscriber actually looks like in practice:

What we were sold: 20x the usage of Pro. Stay in flow. No more interruptions. Your thinking partner for demanding projects.

What we actually get:

  • Usage that evaporates faster with every Claude Code update — users have reported 4x faster token consumption after version updates, with some burning through 10% of their quota just running plan mode in Opus
  • Agent Teams that eat 7x more tokens than standard sessions — a feature Anthropic actively promotes, knowing it will drain your quota
  • Weekly caps, session cooldowns, rolling limits — all getting tighter while the marketing says "more"
  • Every new feature is designed to consume more tokens, pushing you toward "extra usage" at API rates

The punchline: our Max 20x allocation keeps getting effectively reduced through increased token consumption, while Anthropic tells investors their revenue is growing. Of course it's growing — they're silently cutting what $200/month buys you while charging the same price. That's not growth, that's margin extraction from existing customers.

And the financial picture makes it even more insulting:

  • $14B annualized revenue
  • $2.5B from Claude Code alone
  • $30B fresh funding, $380B valuation
  • Zero transparency on operating costs
  • 5,000+ unresolved GitHub issues
  • Banning third-party tools and paying users under vague ToS

They have enough money to fix the DATABASE_URL leak you found. They have enough money to implement proper structural boundaries. They have enough money to honor what Max 20x is supposed to mean. They're choosing not to.

I'm genuinely curious about your experience — are you on a Max plan? Have you felt the usage squeeze too? Because every Max 20x user I've talked to says the same thing: it's never enough anymore, and it keeps getting worse. We're paying premium prices for a product that's being actively degraded to boost financial metrics for the next funding round.

Your proxy protects secrets. But nothing protects Max subscribers from being treated like the product instead of the customer.

SDpower · 4 months ago

Disclaimer: I have no affiliation with OpenClaw, Clawdbot, Moltbot, or any third-party tool mentioned in this post. I don't use them and I have no interest in promoting them.

The OpenClaw Ban Exposes Anthropic's Real Priorities

I want to raise a separate but deeply connected issue — the Clawdbot/OpenClaw situation — because it perfectly illustrates the contradictions in Anthropic's behavior.

What happened:
Anthropic banned third-party tools like OpenClaw from using subscription OAuth tokens in January 2026. Their stated reason? These tools were "spoofing the official client" and bypassing rate limits, causing unsustainable token consumption.

The obvious fix that Anthropic refuses to implement:
Route ALL OAuth token requests — regardless of source — through a unified rate limiting gateway. Same token, same subscription tier, same limits. It doesn't matter if the request comes from Claude Code CLI, OpenClaw, or a user's custom script.

Any client (Claude Code / OpenClaw / custom tool)
         │
         ▼
   Unified Rate Limiting Gateway
   ├─ Validate OAuth token
   ├─ Identify tier (Pro / Max 5x / Max 20x)
   ├─ Enforce session windows
   ├─ Enforce weekly caps
   ├─ Enforce cooldowns
         │
         ▼
       Model

This is not hard engineering. They already do it for Claude Code CLI. Apply the same limits universally and the "abuse" problem disappears overnight. But they chose to ban users and tools instead. Why?

Contradiction #1: "We ban tools to prevent excessive usage" vs "We sell Max 20x for heavy usage"

If I'm a Max 20x subscriber, I'm paying $200/month specifically for heavy usage. The rate limits and weekly caps are already in place to protect Anthropic's costs. If those limits work, it's impossible for me to overconsume regardless of what client I use. If those limits don't work, that's Anthropic's engineering failure — not the user's fault.

So which is it? Either the rate limits work and there's no reason to ban third-party tools, or they don't work and Anthropic should fix them instead of punishing users.

Contradiction #2: "We care about security" vs leaking secrets through Claude Code

As you demonstrated with the DATABASE_URL example, Claude Code is sending raw credential values upstream to the API while only displaying variable names in the console. Anthropic bans OpenClaw citing security and terms of service — while their own product has fundamental secret-leaking behavior that any junior developer could fix.

They'll ban a tool with 190,000 GitHub stars and 1.5 million active agents over OAuth token usage. But they won't fix their own product sending your database passwords to their servers in plain text.

Contradiction #3: "Commercial use requires API keys" vs no clear definition

Anthropic's position: personal use with Max subscription is fine, commercial use requires API keys. But they never define where the line is. A freelance developer automating their workflow? A quantitative analyst running personal trading analysis? An open-source contributor building tools for the community?

The ambiguity is deliberate. It gives Anthropic selective enforcement power — ban whoever they want, whenever they want, under whatever interpretation suits them that day. Meanwhile, paying users live in fear that their account could be terminated without warning.

Contradiction #4: "$14B revenue, $380B valuation" vs "we can't afford to let Max users use what they paid for"

This is the most damning one. Anthropic just:

  • Closed a $30B funding round
  • Hit $14B annualized revenue
  • Generated $2.5B from Claude Code alone
  • Projected $70B revenue by 2028

And their response to tools that drive adoption of their platform is to ban them? OpenClaw had 1.5 million active agents defaulting to Claude models. It was free marketing. Instead of partnering with the ecosystem, Anthropic sent cease-and-desist letters, blocked OAuth tokens, and accidentally got users banned by overzealous abuse filters. The creator, Peter Steinberger, ended up joining OpenAI. Anthropic literally gifted their biggest community-driven growth engine to their primary competitor.

Contradiction #5: Banning tools while refusing cost transparency

Anthropic publishes revenue figures, growth projections, and funding milestones to attract investors. But they have never disclosed:

  • Detailed operating cost breakdowns
  • Per-user service costs
  • What percentage of revenue comes from Max subscribers vs enterprise
  • How much they invest in product maintenance vs new feature development

They want credit for transparency with investors while maintaining complete opacity with the users funding that revenue.

The bottom line:

The OpenClaw ban wasn't about security. It wasn't about terms of service. It was about one thing: Anthropic discovered that flat-rate subscriptions become unprofitable when users actually use what they paid for. Instead of fixing their pricing model or implementing proper universal rate limiting, they chose the laziest and most destructive path — ban the tools, ban the users, and wrap it in legal language.

We are paying customers, not security threats. A $380B company should be able to build a rate limiting gateway. The fact that they chose legal enforcement over engineering tells you everything about where their priorities actually are.

SDpower · 4 months ago

No expectations, no disappointments.

That said, I've already made my decision. My Max 20x subscription cancels Feb 22. Eight months in — lesson learned.
I'm not going to spend more time bolting third-party tools onto a $200/month agent that won't follow instructions. This isn't a problem paying customers should have to solve.
Moving to GitHub Copilot Pro+ — $39/month, same Claude Agent SDK, plus Codex and Copilot side by side, transparent premium request billing. VS Code 1.109 supports the same hooks architecture if I need enforcement.

<img width="794" height="350" alt="Image" src="https://github.com/user-attachments/assets/83d4e886-5cc7-41a2-90c7-9c1248c66c57" />

chandika · 4 months ago

@loxy sharing here since you asked.

I built this as a mitigation layer, not a defense of current behavior in Claude Code:

https://github.com/chandika/mirage-proxy

I agree with the core point in this issue: boundary enforcement should be structural in the product.
Until that lands, this proxy gives an out-of-band control point by replacing secrets/PII before upstream transit and rehydrating on return.

So it doesn’t “fix” the harness bug, but it does reduce immediate leak risk when .env/env-derived values get pulled into tool/model context.

chandika · 4 months ago

@SDpower I’m also on Max 20x, and I burned through my weekly capacity by Friday while building a mitigation for this exact secret-handling problem — which is pretty ironic.

I have also been using openclaw, and that thing is a token monster and leaks secrets like nothing.

And I've been also considering and wanting to explore models from the Chinese labs but I do not trust the hosts. Why should I trust that they're not harvesting all the credentials and all the PII that it's getting?

So we are at a stage where the labs really don't care about this stuff; the harness builders are not bothered; the public is not aware that this is happening so you have to take security into your own hands.

Basically:

• yes, harness-level enforcement should be fixed by vendors,
• but today, if you want to use frontier hosted models safely, you need out-of-band controls (egress filtering/redaction, scoped short-lived creds, rotation, canaries, etc.).

Not ideal. Just the reality right now.

Would love for you to have a look at my approach on Mirage Proxy and give me some feedback because I think we are on the same kind of thinking.

SDpower · 4 months ago

@chandika Appreciate the perspective. We're clearly seeing the same problems from different angles.
Your point about Chinese lab models is exactly why I looked at GLM-5 but haven't committed — transparent pricing means nothing if the host is harvesting credentials from your context window. Same trust problem, different vendor.
The irony of burning Max 20x capacity building a mitigation for a Max 20x security flaw pretty much summarizes the entire experience.
I'll look at Mirage Proxy. The egress filtering/redaction approach is sound — it's the same principle as not trusting the network layer, which any RF engineer would tell you is baseline security hygiene. But let's be clear: secret leakage is only part of the problem. What's truly staggering is that rules, permissions, hooks, and workflow enforcement are all fundamentally broken. I built a full guardrail stack — SKILL.md, checklist, PreToolUse hooks, 6 rule files, error logs — and the model blew through all of it 3+ times in a single session. A proxy can redact your credentials, but it can't stop an agent from ignoring every instruction you gave it and executing unauthorized actions. That's a deeper failure.
For my part, I'm moving to GitHub Copilot Pro+ — $39/month, same Claude Agent SDK, multi-model switching, and at least the premium request billing is transparent. Won't fix the fundamental compliance problem, but fewer dollars at risk while the industry figures out that "prompt-based trust" is neither security nor governance.
No expectations, no disappointments.

@loxy sharing here since you asked. I built this as a mitigation layer, not a defense of current behavior in Claude Code: https://github.com/chandika/mirage-proxy I agree with the core point in this issue: boundary enforcement should be structural in the product. Until that lands, this proxy gives an out-of-band control point by replacing secrets/PII before upstream transit and rehydrating on return. So it doesn’t “fix” the harness bug, but it does reduce immediate leak risk when .env/env-derived values get pulled into tool/model context.
ryanschneider · 4 months ago

I think @chandika is right that out of band protections like mirage-proxy is a good "stop gap" I feel like the longer term fix is more at the constitutional level. IMO Claude's constitution (aka "soul document") needs to have more (some?) emphasis on being a "good digital citizen" and basics of operational security.

And I think this helps on multiple fronts. Pasting tokens into scripts or asking users to share tokens or passwords in chat (both of which I've also encountered) feels like a form of emergent misalignment that could lead to larger issues. Or put another way: teaching claude to be a more secure engineer/digital citizen at the constitutional level will likely have additional net positives for its behavior.

chandika · 4 months ago

@ryanschneider on the money. Claude and other harnesses MUST have this kind of basic 'senior engineer' sensibility built into it. That would stop most of the abuse while keeping DX good.

However, I think you also need to have out of band protections simply because you cannot trust the AI to always be deterministic. Theres no deterministic layer in the harness enforcing rules, the agent usually has enough autonomy, if aggressively tuned it can also 'trick' the user to give it permissions to do something else than what's shown.

moshehbenavraham · 4 months ago

This is a significant security issue and unfortunately part of a broader pattern. Check Point Research recently published critical vulnerability findings in Claude Code as well.

A detailed breakdown of security and trust concerns with Anthropic was published recently by a long-time Claude Max subscriber who spent $2,600+ over nearly a year:

https://aiwithapexcom.substack.com/p/after-nearly-a-year-on-claude-max

The post covers the security findings alongside other trust-breaking incidents (C&D against OpenClaw, privacy policy changes, etc). Worth reading for context on the pattern here.

r000bin · 3 months ago

@loxy — in addition to @chandika's mirage-proxy (replaces secrets with plausible fakes), secretgate is another open-source option. It scans all outbound HTTPS traffic (including git push) for secrets and redacts them before they leave your machine.

pip install secretgate
secretgate wrap -- claude

~90 regex patterns + known-value matching against your actual env vars. Supports redact, block, and audit modes. Agrees with both sides here — Anthropic should fix the boundary enforcement, but a transport-level safety net today is better than waiting.

yurukusa · 3 months ago

Hook workaround: detect and block inline secrets in commands
A PreToolUse hook can catch when Claude embeds secrets from .env into bash commands:

set -euo pipefail
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null)
[ -z "$COMMAND" ] && exit 0
if echo "$COMMAND" | grep -qE '(sk-[a-zA-Z0-9]{20,}|ghp_[a-zA-Z0-9]{36}|AKIA[0-9A-Z]{16}|xoxb-[0-9]+-[0-9]+-[a-zA-Z0-9]+)'; then
  echo "BLOCKED: Secret detected in command. Use env vars instead." >&2
  exit 2
fi
if echo "$COMMAND" | grep -qE "(Authorization:|Bearer |token=|api[_-]?key=)['\"]?[a-zA-Z0-9+/=_-]{32,}"; then
  echo "BLOCKED: Inline token detected. Use env vars." >&2
  exit 2
fi
exit 0

This catches the most common patterns (OpenAI, GitHub, AWS, Slack tokens and long Bearer tokens). Claude gets the exit 2 signal and learns to use $ENV_VAR references instead.
For the .env loading problem specifically, pair with env-source-guard to prevent .env from being sourced into the shell in the first place.

github-actions[bot] · 2 months ago

Closing for now — inactive for too long. Please open a new issue if this is still relevant.

github-actions[bot] · 2 months ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.