Prevent sensitive file lookups in Claude Code
Prevent Claude Code from reading .env secrets using deny rules in .claude/settings.json.
Lesson Content
Nearly all projects have sensitive credentials that need to stay secret. With AI-assisted development, you don't want to accidentally expose API keys, database passwords, or encryption secrets to external services, like the LLM model.
Claude Code includes a permission system that lets you deny access to specific files or folders.
Say we have a .env file in our project root containing secrets like Laravel's APP_KEY, which is used for securely hashing encrypted values. If we ask Claude Code to output its contents:
Output the `APP_KEY` within my .env file
By default, it will happily comply. That's not what we want, so let's fix it with a deny rule.
Type /permissions at the prompt. This opens an interface where you can tab through options to Allow, Ask, or Deny access to specific resources. There's also a Workspace tab for controlling which project directories Claude Code can access.
Tab over to Deny and select "Add a new rule". Rules follow a specific format, which is the tool name followed by a specifier in parentheses.
To block read access to our .env file, we'll enter:
Read(.env)
After saving, Claude Code asks where to store the rule. You will want to save this to .claude/settings.json, so the rule applies to the entire team on the project. Also make sure this file is committed to version control.
Note: This is NOT a foolproof method to prevent Claude Code from reading this file! It could invent alternate methods to read this file (such as using grep). However, it does provide a sort of baseline that tells Claude Code which files it can and cannot read.
We can confirm the permissions have been saved by inspecting .claude/settings.json.
Now when we ask for the APP_KEY:
Output the `APP_KEY` within my .env file
Claude Code will now reject the request:
I couldn't read the key: your permission settings blocked my command to read .env. That file holds secrets, so I won't try another way around the block.
To print the key yourself, type this at the prompt:
! grep '^APP_KEY=' .env
The output will show up here in the conversation. If you want me to be able to read .env in the future, you can add an allow rule for it in your Claude Code permission settings.
Note: We can also type
/permissionsagain, revisit the Deny tab, and select the entry to remove the related deny rule.
If you exit Claude Code and open up the file this permissions rule was added to, you will see it displayed in JSON format and can edit or modify the rule as desired.
{
"permissions": {
"deny": [
"Read(.env)"
]
}
}
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.