TL;DR: Master API key management best practices by never storing unencrypted secrets in git, enforcing automated secrets scanning, and avoiding plaintext sharing in messaging systems. Use dedicated secrets management tools, apply least privilege and short-lived keys, and implement robust rotation and monitoring strategies.
We have compiled a list of some of the best practices to prevent API key leakage and keep secrets and credentials safe. Secrets management doesn't have a one-size-fits-all approach, so this list considers multiple perspectives so you can be informed in deciding to or not to implement strategies.
Never store unencrypted secrets in .git repositories
It is common to wrongly assume that private repositories are secure vaults that are safe places to store secrets. Private repositories are not appropriate places to store secrets.
Private repositories are high-value targets for bad actors because it is common practice to store secrets within them. In addition, .git is designed to sprawl. Repositories get cloned onto new machines, forked into new projects and new developers regularly enter and exit a project with access to complete history. Any hard-coded secrets that exist within a private repository's history will exist in all new repositories born from that source.
If a secret enters a repository, private or public, then it should be considered compromised.
A secret in a private repo is like a password written on a $20 bill, you might trust the person you gave it to, but that bill can end up in hundreds of peoples hands as a part of multiple transactions and within multiple cash registers.
If already committed and want to remove an API key from the git history, see: Git Clean, Git Remove file from commit - Cheatsheet
Avoid git add * commands on git
Using wildcard commands like git add * or git add . can easily capture files that should not enter a git repository. This includes generated files, config files, and temporary source code. When making a commit, you should preferably add each file by name and use git status to list tracked and untracked files.
Advantages: Complete control and visibility over what files are committed. Reduces the risk of unwanted files entering source control.
Disadvantages: Takes additional time when making a commit. Can mistakenly miss files when committing.
TIP: Committing early and committing often will not only help navigate file history and break up otherwise large tasks, in addition it will reduce the temptation to use wildcard commands.
Add sensitive files in .gitignore
To prevent sensitive files from ending up within git repositories a comprehensive .gitignore file should be included with all repositories and include:
- Files with environment variables like
.envor configuration files like.zshrc,application.propertiesor.config - Files generated by another process (such as application logs or checkpoints, unit tests/coverage reports)
- Files containing "real" data (other than test data) like database extracts.
GitHub published a collection of useful .gitignore templates.
Don't rely on code reviews to discover secrets
It is extremely important to understand that code reviews will not always detect hard-coded secrets, especially if they are hidden in previous versions of code. Reviewers are only concerned with the difference between the current and proposed states of the code; they do not consider the entire history of the project.
If secrets are committed to a development branch and later removed, these secrets won't be visible or of importance to the reviewer. The nature of git means that if a secret gets overlooked in history it is exposed forever.
TIP: As a rule, automation should be implemented wherever predefined rules can be established, like secrets detection. Human reviews should be left to check code for errors that cannot be easily predefined, such as logic.
Use automated secrets scanning on repositories
Even when all best practices are followed, mistakes are common. GitGuardian offers a free secrets scanning solution for developers to detect both generic API keys and specific secrets (more than 450 providers are supported!), installable both on private and public repositories for free.
Visibility is the key to great secret management. If you don't know you have a problem, you cannot take action to fix it.
Don't share your secrets unencrypted in messaging systems like Slack
A common secret sprawl enabler is sending secrets in plain text over messaging services. These systems are high-value targets for attackers. It only takes one compromised email or Slack account to uncover a trove of sensitive information, as secrets exposure extends beyond source code into various communication and collaboration tools.
Store secrets safely
There is no silver bullet solution for secrets management. Different factors such as project size, team geography, and project scope, must be considered. Multiple solutions may need to coexist.
Use encryption to store secrets within .git repositories
Encrypting your secrets using tools such as git secret or SOPS and storing them within a git repository keeps secrets synced across teams.
Advantages: Your secrets are synced. Disadvantages: You have to deal with your encryption keys securely. No audit logs. No RBAC. Hard to rotate access.
Use local environment variables when feasible
An environment variable is a dynamic object whose value is set outside of the application. This makes them easier to rotate without having to make changes within the application itself.
Advantages: Easy to change between deployed versions without changing any code. Less likely to be checked into the repository. Simple and clean.
Disadvantages: May not be feasible at scale when working in teams — no easy way to keep developers, applications, and infrastructure in sync.
Use Secrets Management Tools
Secrets management systems such as Hashicorp Vault or AWS Key Management Service are encrypted systems that can safely store your secrets and tightly control access.
Advantages: Prevents secrets from sprawling. Provides audit logs.
Disadvantages: Must be hosted on highly-available and secure infrastructure. Requires codebase changes to integrate. Access keys must be carefully protected.
Restrict API access and permissions
By restricting the access and permissions of the API key you not only limit damage and restrict lateral movement but also provide greater visibility over when the API key is being used outside of its scope.
💡 This idea can be pushed even further by using API keys as a decoy to intercept hackers — a concept called a honeytoken. Learn more about the Honeytoken module in GitGuardian.
Default to minimal permission scope for APIs
Make sure the permissions of that API match the task it is fulfilling. Have separate APIs for read-only and read/write permissions to avoid overprivileged secrets. It is common for developers to use API keys with excessive permissions — this increases the potential damage of a data breach.
Whitelist IP addresses where appropriate
IP whitelisting provides an additional layer of security by providing a whitelist of IP addresses from your private network so external services only accept requests from trusted sources.
Advantages: Limited requests to select trusted sources. Disadvantages: Not always feasible. Can prevent legitimate requests. Needs constant maintenance.
Use short-lived secrets
By using short-lived secrets, the risk of undetected leaked API keys is mitigated, ensuring that even if an attacker gains access to a secret, it would be harmless, unlike most exposed secrets that remain valid for extended periods.
Revoke and rotate all API keys often to prevent unrevoked secrets from lurking in your systems.
Imagine you own a company with hundreds of employees that all have keys to your office — keys will inevitably get lost, employees will leave, new keys will get cut and you will soon lose visibility over where each key is. It would be widely considered good practice to change the locks from time to time.
Advanced API Key Storage and Cryptographic Protection
Enterprise API key management demands sophisticated storage mechanisms with cryptographic protection layers. Single-purpose keys are a fundamental principle — use dedicated keys for encryption versus authentication to prevent cryptographic side effects.
For applications requiring local key storage, implement Hardware Security Modules (HSMs) or secure enclaves. When HSMs aren't feasible, use secure key generation through cryptographically secure random number generators. Consider key derivation strategies where multiple API keys derive from a single master key using strong secret diversification methods.
API Key Monitoring and Anomaly Detection
Implement monitoring systems that track API key usage patterns — request frequency, geographic distribution, and accessed resources — to establish baseline behaviors. Deploy alerting for suspicious activities such as unusual request volumes, unexpected IP ranges, or attempts to access resources outside normal scope.
Establish audit trails capturing successful API calls, failed authentication attempts, permission escalations, and administrative changes. Integrate with SIEM systems to enable real-time threat detection and automated response workflows.
Conclusion
Managing and storing secrets is a challenge that requires vigilance from even the most experienced developer. There is no perfect checklist that a developer can follow.
Policies, tools, and strategies will differ from project to project, but it is crucial for developers to understand the consequences of their choices so that secrets management can be an informed, active strategy throughout the entire development process.
Summary: Best Practices for API Key and Credentials Security
- Never store unencrypted secrets in .git repositories — avoid wildcard git add, use .gitignore, use automated scanning
- Don't share secrets unencrypted in messaging systems like Slack
- Store secrets safely — use encryption, environment variables, or secrets-as-a-service solutions
- Restrict API keys access and permissions — minimal scope, IP whitelisting, short-lived secrets
💡 Ready to find out which secrets management approach is right for you? Take the GitGuardian Secrets Management Needs Quiz
FAQs
What are the most critical API key management best practices for large development teams?
Core best practices include avoiding unencrypted secrets in Git repositories, enforcing automated secrets scanning, and applying least-privilege policies to all keys. Regular key rotation, centralized secrets management, and encryption of all credentials both at rest and in transit are essential.
How should organizations approach API key rotation and lifecycle management?
Automate rotation schedules based on privilege and risk: rotate high-privilege keys weekly or daily, and rotate low-privilege keys monthly. If any key in a rotation chain is compromised, revoke all related keys immediately.
Why is relying solely on code reviews insufficient for detecting hard-coded secrets?
Code reviews typically cover only recent changes and may overlook secrets committed previously and later removed. These secrets persist in repository history and remain exploitable. Automated secrets scanning provides comprehensive coverage across current code and historical commits.
What advanced storage options are recommended beyond environment variables?
Robust alternatives include dedicated secrets managers (e.g., HashiCorp Vault, AWS Secrets Manager), Hardware Security Modules (HSMs), and secure enclaves offering cryptographic protection, granular permissioning, and automated rotation.
How can organizations monitor API key usage and detect anomalies?
Monitor request volume, originating IP addresses, time-of-day patterns, and resource access behavior. Configure alerts for unusual activity and forward logs to SIEM platforms for real-time analytics and automated incident response.
What are the risks of sharing secrets in messaging platforms like Slack?
Sharing secrets in plaintext on messaging platforms exposes them if accounts are compromised. Attackers can exploit these credentials for lateral movement or privilege escalation. Always use dedicated secrets management tools to share sensitive information securely.


Top comments (0)