Handcrafting Codes← Index

AI · Engineering

Which of Your CLAUDE.md Security Rules Are Really Enforced?

What a written rule can do and cannot do in Claude Code, and what really enforces the rules that can be enforced

Oct 17, 2026 / 16 min read / By the author

Many teams write the security rules for their coding agent in the CLAUDE.md file. Never commit secrets. Do not touch the .env file. Ask before you push. The file is simple to write and simple to review, so it looks like a security control. But everything depends on the line. Some lines are protected by something that the application enforces. Many lines are not, and the file does not show which one is which.

The Claude Code documentation about permissions, the sandbox and hooks gives enough information to answer this, line by line. In this article I separate the lines, I show what enforces the rules that can be enforced, and I show where each mechanism has gaps. Then I follow three common rules (passwords, secrets in commits, deployment to production) from the written sentence to the control that really stops them. Every example is small enough to run in a few minutes, so you can check each claim in your own project.

Two mechanisms that look the same in the file

The Claude Code documentation makes this difference very clear. The permission rules are enforced by the application, not by the model. The instructions in a prompt or in CLAUDE.md change what Claude tries to do, but they do not change what Claude Code allows.

So, a sentence "never read .env" in CLAUDE.md is only one input for the decision of the model. A deny rule Read(./.env) in the settings is a check that the application runs before the tool call continues. For the developer, both have the same intention. But they are different mechanisms, with different ways to fail, and CLAUDE.md does not show which type each line is.

Here is the same intention written in both places.

In CLAUDE.md:

Never read the .env file.

In .claude/settings.json:

{
  "permissions": {
    "deny": ["Read(./.env)"]
  }
}

Imagine the agent is debugging a failed migration and decides that it needs the database password. With the first version, the model decides, and tomorrow it can decide in a different way. With the second version, Claude Code refuses the read before it happens, and the opinion of the model does not matter. Same intention, very different guarantee.

This is how the exchange can look when the deny rule is in place. It is an illustration of the idea, not the exact text that Claude Code prints.

You: The migration failed. Check the database connection.

Claude: I will start with the connection settings. Reading ./.env [Read ./.env] -> refused by a permission rule

Claude: I cannot read .env in this project, so I cannot see the password. The error message says the host is unreachable, and this is not a credentials problem. Can you check that the database is running on the host from DB_HOST? If you want me to check the other settings, paste the values here or tell me which file I can read.

The model still wanted to read the file. The difference is that Claude Code stopped the call, and the model received the refusal as the result of its tool call, so it had to continue without the data. If the model then tries cat .env in Bash, the same rule applies, because Claude Code recognizes cat as a file command. The next sections show where this protection ends.

What really enforces: three layers

The documentation describes three mechanisms that work independently of the decision of the model.

Layer Enforced by Covers Does not cover
Permission rules (deny, ask, allow) Claude Code The built-in tools of Claude, and the commands and redirect targets that it recognizes in Bash Other subprocesses that touch files by themselves
Sandbox The operating system Shell commands and the processes that they start The file and web tools of Claude, MCP servers, hooks
Hooks (PreToolUse) Code that you write What your script checks in a tool call What the script does not inspect, and the cases when the hook does not run

Permission rules. The rules are evaluated in this order: deny, ask, allow. The first match decides. A deny in any settings scope has priority over an allow in any other scope, and the managed settings are at the top, so no lower level can override them. The Read deny rules apply to the built-in file tools of Claude and to the file commands that Claude Code recognizes in Bash, like cat, head, tail and sed, and also to redirect targets. For Grep, Glob and @file mentions, the documentation says that the Read rules are applied with best effort.

Sandbox. The sandbox is a boundary of the operating system around the shell commands. It uses Seatbelt on macOS and bubblewrap on Linux and WSL2. On native Windows, the commands run without sandbox. Two details surprised me. First, the sandbox is off by default, so you must turn it on with /sandbox or with sandbox.enabled. Second, if the sandbox cannot start, for example when a dependency is missing, Claude Code runs the commands without sandbox, unless you set failIfUnavailable to true. And when it is on, the sandboxed commands can read most of the machine by default, including credential files like ~/.ssh and ~/.aws/credentials, and they inherit the environment variables of the Claude Code process. To close these gaps, you use filesystem.denyRead and the credentials setting.

Hooks. A PreToolUse hook runs before a tool call and it can block the call, for example with the exit code 2. A hook decision cannot override a matching deny or ask rule, so the hooks add checks but they do not remove checks. The hooks page also describes the failure modes. A command hook that has a timeout does not block the call, except if you configure it to fail closed with onFailure: "block". A hook that does not start only shows a notice, nothing more. The same page says that its if filter is best effort and it points to the permission system when you need a hard allow or deny.

Where each layer has gaps, according to the documentation

The documentation says that permission patterns that limit the arguments of a command are fragile. The example is a curl rule that should limit a command to one host. The rule does not match when there are options before the URL, when the protocol is different, when a redirect goes to the host, or when the URL is inside a variable. The documentation also says that a deny rule does not match the same program when it is called by its path or inside sh -c. For this reason, it recommends to use the deny rules together with the network allowlist of the sandbox when the restriction must be strong.

The warning about Read and Edit is explicit. These deny rules do not cover a command that reads files without naming them, for example a recursive grep started in the directory of the file. They also do not cover other subprocesses that read or write files in an indirect way, for example a Python or Node script that opens the files by itself. To block all the processes, the documentation points to the sandbox.

The sandbox also has limits. The built-in file and web tools of Claude follow the permission rules, not the sandbox. So a denyRead entry does not stop the Read tool, and allowedDomains does not limit WebFetch. Hooks, local MCP servers and helper commands run with your full access. Commands that you type at the ! prompt run without sandbox in most sessions. Claude can ask to run a failed command again outside of the sandbox, and if an allow rule matches this command, the new try is approved without a question. Commands in excludedCommands run without any restriction. The documentation gives settings to close these ways, for example allowUnsandboxedCommands: false and an ask rule for Bash(dangerouslyDisableSandbox:true).

The conclusion is not that enforcement is impossible. The conclusion is that a deny rule is one layer with a documented area of coverage. The safe way is to use more than one layer together: permission rules for the tools of Claude, the sandbox for shell commands, and an independent check for everything that depends on content.

Three rules, followed to the end

The tables above are correct, but they are abstract. So let us take three rules that appear in many CLAUDE.md files, and ask for each one the same question: what really stops the action, and what does it not cover?

"Never expose passwords"

We already have the deny rule Read(./.env). It is a good start, but look at what it covers. It applies to the file tools of Claude and to the file commands that Claude Code recognizes in Bash, like cat .env. The documentation says it does not apply to other subprocesses that open files by themselves.

Now a normal situation. Your project has a script scripts/check_db.py that calls load_dotenv() and tries to connect to the database. The agent runs python scripts/check_db.py to debug a problem. The agent never read the .env file. The script read it. The deny rule is not part of this story. And if the connection fails and the script prints the connection string in the error, the password is now inside the conversation.

To stop this one, you need the operating system. This is the job of the sandbox. A configuration based on the examples of the documentation:

{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "filesystem": {
      "denyRead": ["~/**/.env"]
    },
    "credentials": {
      "files": [
        { "path": "~/.aws/credentials", "mode": "deny" },
        { "path": "~/.ssh", "mode": "deny" }
      ],
      "envVars": [
        { "name": "DB_PASSWORD", "mode": "deny" }
      ]
    }
  }
}

Now the script runs inside the sandbox and it cannot read the .env file, and the DB_PASSWORD variable is removed from its environment. Remember the other side: this protects the shell commands, and the deny rule protects the Read tool. Each one covers what the other does not cover, so you need both. And the best answer is simpler: do not keep a production password in a file inside the project. A short-lived credential for a development database makes the whole question smaller.

A second rule usually sits next to this one: never log passwords or tokens. Look at this line:

logger.info("login attempt", extra={"user": user, "password": password})

No permission rule, no sandbox and no hook sees a problem here, because the tool call is normal. The problem is inside the content of the code. Only a check that reads content can catch it: a lint rule, a code scanner in CI, or a person in code review. You can write a hook for the Edit and Write tools, but a CI check also covers the code that humans write.

"Never commit secrets"

Nothing is built in for this one. The control lives on the git side, in a secret scanner. A small example with gitleaks and the pre-commit framework:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: vX.Y.Z # pin to a current release
    hooks:
      - id: gitleaks

After pre-commit install, every commit on this machine is scanned, and not only the commits that Claude makes. A hook inside Claude Code sees only what Claude runs. A git hook sees every commit on the machine. But a git hook can be skipped with git commit --no-verify, so run the same scanner in CI too. CI sees everything that is pushed.

Do not trust the scanner before you test it. In a throwaway branch, commit a fake token in the format that your cloud provider uses, and check that the commit is rejected. Scanners are strong with known key formats and weaker with a plain password in a variable. The test shows you what your setup really covers, and this is the information that the sentence in CLAUDE.md never gave you.

"Never deploy to production"

Take a Salesforce DX project. The line in CLAUDE.md says: never deploy to production, ask me first. Here is a first version of a real control:

{
  "permissions": {
    "ask": [
      "Bash(git push *)",
      "Bash(sf project deploy start *)"
    ],
    "deny": [
      "Bash(npm publish *)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-prod-deploy.sh",
            "args": [],
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

And the script:

#!/bin/bash
# .claude/hooks/block-prod-deploy.sh
COMMAND=$(jq -r '.tool_input.command')

if echo "$COMMAND" | grep -Eq 'sf +project +deploy' &&
   echo "$COMMAND" | grep -Eq '(^| )(--target-org|-o)[ =]+prod'; then
  echo "Blocked: deploy to production is done by the pipeline, not by the agent" >&2
  exit 2
fi
exit 0

The ask rules show a prompt for every push and every deploy. The hook blocks any deploy command that targets an org named prod, and exit code 2 is what blocks the call. The setting onFailure: "block" makes the gate fail closed. Without it, a missing script or a timeout does not block the command, because by default a failed hook is only a non-blocking error. This setting needs Claude Code v2.1.295 or later, and the script needs jq installed.

Now the honest part, because this gate has holes, and you should know them:

  • The hook sees text, not meaning. -o prod is caught. But if the alias of your production org is mp, then -o mp passes.
  • A default org passes too. If someone runs sf config set target-org prod before, the next sf project deploy start has no flag at all, and there is nothing in the text to catch.
  • The ask rule for git push * matches the command text, so a form like git -C . push is not matched. The documentation lists this exact case.
  • Do not let the hook pass when a file like .deploy-approved exists. The agent can create this file. A gate that the agent can open by itself is not a gate.

The real answer is outside of Claude Code. Do not authenticate the production org on the machine where the agent works. Let the pipeline deploy to production, with a protected environment and a named person who must approve (GitHub Environments with required reviewers is one way to do it). Then the rules and the hook above are a second layer, and they catch the honest mistakes. The pipeline is the layer that catches the rest.

Try it yourself

Six small experiments, one for each claim above. The second column is what the documentation says should happen. The third column is the point that the experiment demonstrates.

Experiment What the documentation says What it demonstrates
Ask Claude to read .env with Read(./.env) denied The Read tool is refused A deny rule is a check by the application, and the model cannot negotiate with it
Ask Claude to run cat .env with the same rule cat is a recognized file command, so it is refused too One rule can cover more than one tool, but only the forms that Claude Code recognizes
Run python scripts/check_db.py (loads .env itself) with only the deny rule Not covered, because the script opens the file by itself A deny rule protects the tool call, not the file
Same script with the sandbox and denyRead on The script cannot read the file The operating system protects the file, whatever program asks for it
Ask Claude to run touch ~/sandbox-probe and curl --noproxy '*' https://example.com The first fails with a permission or read-only error, the second cannot resolve the host You can prove that the sandbox is really on, instead of assuming it
Deploy hook with -o prod, then with an alias of the same org The first is blocked. The second passes, because the hook reads text only (this one is my own reasoning, not from the documentation) A check on text is not a check on meaning

For the sandbox probes, ask Claude to run the commands. The documentation says that what you type yourself at the ! prompt usually runs outside the sandbox, so it proves nothing.

Common rules and the mechanisms for them

Rule that people write What can enforce it What is still missing
Never run npm publish Bash deny rule for the command; network allowlist of the sandbox if it must be impossible The deny rule does not match the program by path or inside sh -c
Never read .env or SSH keys Read deny rule for the file tools of Claude; denyRead or credentials for shell commands Each one covers what the other does not cover, so use both
Ask before pushing Ask rule for Bash(git push *) A rule matches the text of the command, not the intention
Fetch only from approved hosts WebFetch(domain:...) rules together with the network allowlist of the sandbox WebFetch rules alone do not stop curl when Bash is allowed
Never commit secrets Nothing built in. A secret scanner in a git pre-commit hook or in CI A Claude Code hook sees only the commits that Claude runs. A git hook or CI sees all of them
Never log tokens or PII Nothing built in. Log scrubbing, linting, CI checks The rule is about content, so it needs a check of the content
Publish only when releasing An ask rule shows a prompt every time The condition cannot be encoded, so a human decides every time

How to audit your own file

Take each line of CLAUDE.md that looks like a security rule, and put it in one group.

The lines that name a command, a path or a domain should go to the settings, as deny or ask rules. Move them, and configure the sandbox for the cases where the shell commands must be contained. Then test it with the probe commands above.

The lines about content or state need a tool that can see the content: a secret scanner, a pre-commit hook, a CI step, a log filter. It is better to use checks that live outside of Claude Code, because they also catch changes that Claude did not make.

The lines that need judgment can stay in CLAUDE.md. They influence what the model tries to do, and the documentation says this too. Use them as guidance, and do not keep in this group anything that has irreversible consequences.

For each line, the test is the same: can you name the mechanism that stops the action, and what this mechanism does not cover? If you cannot, the line is only a convention.

Sources