API Keys Security & Secrets Management Best Practices - GitGuardian Blog (2024)

Storing and managing secrets like API keys and other credentials can be challenging. Even the most careful policies can sometimes be circumvented in exchange for convenience. 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.

Directory

  • Never store unencrypted secrets in .git repositories
    • Avoid git add * commands on git
    • Add sensitive files in .gitignore
    • Don’t rely on code reviews to discover secrets
    • Use automated secrets scanning on repositories
  • Don’t share your secrets unencrypted in messaging systems like Slack
  • Store secrets safely
    • Use encryption to store secrets within .git repositories
    • Use environment variables
    • Use "Secrets as a service" solutions
  • Restrict API keys access and permissions
    • Default to minimal permission scope for APIs
    • Whitelist IP addresses where appropriate
    • Use short-lived secrets

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, follow the guidelines below:

Git Clean, Git Remove file from commit - Cheatsheet - GitGuardian BlogExposing secrets in a git repository is bad but mistakes happen. This is a complete guide and cheatsheet to rewrite and remove files from git historyGitGuardian Blog - Automated Secrets DetectionGuest Expert

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.

To avoid that, when making a commit, you should preferably add each file by name and use git status to list tracked and untracked files. According to git-scm:

“Remember that each file in your working directory can be in one of two states: tracked or untracked.
Tracked files are files that were in the last snapshot; they can be unmodified, modified, or staged. In short, tracked files are files that Git knows about.
Untracked files are everything else.”

Advantages

  • Complete control and visibility over what files are committed
  • Reduces the risk of unwanted files entering source control and API key leak
  • Requires thought and consideration when adding files

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 .env or configuration files like .zshrc, application.properties or .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. See these examples for Python or Go.

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. The reason code reviews are not adequate protection is because 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.

API Keys Security & Secrets Management Best Practices - GitGuardian Blog (4)

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 as anyone with access to the repository can find this secret in previous revisions of the codebase.

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. When dealing with highly sensitive data, no chances should be taken. GitGuardian offers a free secrets scanning solution for developers to detect both generic API keys and specific secrets (more than 350 providers are supported!).

But the best is that it can be installed 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. Secrets scanning provides essential visibility over your internal systems.

It is important to also consider that even the best secrets management systems and policies do not prevent newly generated secrets from entering the code base or old secrets from being extracted and included again.

Advantages

  • Difficult to circumvent and ignore compared to tools that need to be manually run
  • Much faster and more accurate than relying on human checking
  • Can detect secrets buried within logs and history that manual reviews and searches will not uncover
  • Live scanning ensures all active data leaks are captured

A common secret sprawl enabler is sending secrets in plain text over messaging services. While these systems are intended to keep messages secure, they are not intended to hold sensitive information such as secrets.

These systems are high-value targets for attackers. It only takes one compromised email or Slack account to uncover a trove of sensitive information. If secrets are being sent over internal systems, it also makes it possible for bad actors to move laterally between services by ‘using secrets to find secrets’.

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. Carefully consider each option, not just to meet your current needs but also to consider how each solution will scale with the growth of your project.

Use encryption to store secrets within .git repositories

Encrypting your secrets using common tools such as git secret or SOPS and storing them within a git repository can be beneficial when working in teams as it keeps secrets synced.

However, it's important to note that this approach introduces a new challenge—managing additional security keys for encryption and decryption, as well as securely sharing them. This aspect may seem like an ongoing concern, but it's a vital aspect to address for robust security practices.

Advantages

  • Your secrets are synced

Disadvantages

  • You have to deal with your encryption keys securely
  • No audit logs (who accessed which secret and when)
  • No role-based access control (RBAC)
  • Hard to rotate access. Rotating access implies revoking the key and redistributing it. The distribution part is not easy to handle with git repositories when dealing with multiple developers

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. It also removes the need to have these written within source code, making them more appropriate for handling sensitive data.

Advantages

  • They are easy to change between deployed versions without changing any code
  • They are less likely to be checked into the repository
  • Simple and clean

Disadvantages

  • This approach may not be feasible at scale when working in teams because there is no way to easily keep developers, applications, and/or infrastructure in sync.

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. Vaults and other managed secrets solutions are not appropriate in all cases because they are complicated to set up and need to be well maintained. Both take a considerable investment of resources.

Advantages

  • It prevents secrets from sprawling
  • It provides audit logs

Disadvantages

  • As they introduce a single point of failure, they must be hosted on a highly-available and secure infrastructure
  • All the codebase must be changed to integrate with them
  • Keys giving access to the system must be carefully protected

It can be difficult to detect when an attacker is using secrets like API keys maliciously because they are often using them within their scope. 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.

💡

In fact, this idea can be pushed even further by using API keys as a decoy to intercept hackers! This concept is called a honeytoken. Learn more about the Honeytoken module in GitGuardian.

Default to minimal permission scope for APIs

When using external services, make sure the permissions of that API match the task it is fulfilling. This includes making sure you have separate APIs for read-only and read/write permissions as needed.

Many APIs also allow you to have increased control over what data can be accessed. For example, the Slack API has a large range of scopes, and restricting these scopes to meet the task's minimal requirements of the task is important to prevent an attacker from accessing sensitive data. It is common for inexperienced developers to use API keys with excessive permissions allowing them to use one key throughout their project. But this increases the potential damage of a data breach. Learn about Identity and Access Management best practices here:

IAM Best Practices [cheat sheet included]Download our cheat sheet on IAM, Identity and Access Management, best practices. It will help you make your cloud environments more secure.GitGuardian Blog - Automated Secrets DetectionDwayne McDaniel

Whitelist IP addresses where appropriate

IP whitelisting provides an additional layer of security against bad actors attempting to use APIs nefariously. By providing a whitelist of IP addresses from your private network, your external services will only accept requests from those trusted sources. It is common to include a range of acceptable IP addresses or a network IP address.

In an example from GitHub, you can use IP whitelisting to prevent any untrusted sources from accessing your GitHub repositories. “The allow list for IP addresses will block access via the web, API, and Git from any IP addresses that are not on the allow list.”

Advantages

  • Limited requests to select trusted sources and prevents attacks from external sources even with secret keys

Disadvantages

  • Not always feasible depending on the traffic the source is expecting
  • Can prevent legitimate information requests
  • Needs to be maintained constantly

Use short-lived secrets

It is common for APIs to typically provide long-lasting (or long-lived) access tokens. These tokens could last indefinitely. While this is convenient for developers, it means that a secret poses the same security risks for its entire life and increases the chances of them being used in an attack. 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.

It is also good practice to make sure you revoke and rotate all API keys often, particularly if it is not possible to introduce a validity period on APIs.

Imagine you own a company with hundreds of employees that all have keys to your office, keys will inevitably get lost, employees will leave the company, 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.

Advantages

  • Enforces good secret hygiene
  • Reduces the risk of long-term threats

Disadvantages

  • Requires an active secrets management strategy

Managing secrets and storing secrets is a challenge that requires vigilance from even the most experienced developer, who needs to carefully consider how they are using, storing, sharing, and distributing secrets. Unfortunately, there is no perfect checklist that a developer can follow.

Policies, tools, and strategies will differ from projects, but it is crucial for developers to understand the consequences of policies so that secrets management can be an informed, active strategy throughout the entire development process.

Summary: Best Practices for API Key and Other Credentials Security

  1. Never store unencrypted secrets in .git repositories
    • Avoid git add * commands on git
    • Add sensitive files in .gitignore
    • Don’t rely on code reviews to discover secrets
    • Use automated secrets scanning on repositories
  2. Don’t share your secrets unencrypted in messaging systems like Slack
  3. Store secrets safely
    • Use encryption to store secrets within .git repositories
    • Use environment variables
    • Use "Secrets as a service" solutions
  4. Restrict API keys access and permissions
    • Default to minimal permission scope for APIs
    • Whitelist IP addresses where appropriate
    • Use short-lived secrets

If you want comprehensive guidelines on how to handle secrets with popular DevOps tools such as Docker, Jenkins, Python, AWS, or Kubernetes, have a look at this GitGuardian collection of articles:

How to handle secrets in XIn this series of articles, GitGuardian specialists answer all the questions you never dared to ask on secrets management. Secrets at the Command Line [cheat sheet included]Developers need to prevent credentials from being exposed while working on the command line. Learn how you might be at risk an…GitGuardian Blog - Automated Secrets DetectionZiad Ghalleb

Finally, if you want to accelerate your learning journey in the world of code security, dive into our collection of cheat sheets: from how to correctly set up multiple GitHub accounts, using GitHub Actions, or manipulate secrets on the command line to understanding IAM best practices, securing infrastructure as code and Docker.

And much more!

💡

Ready to find out which secrets management approach is right for you? Take the GitGuardian Secrets Management Needs Quiz right now at

https://www.gitguardian.com/secrets-management-guide
API Keys Security & Secrets Management Best Practices - GitGuardian Blog (2024)

FAQs

What is the best practice for API key rotation? ›

If you want to be great at API key rotation, you need to:
  • Record where your keys are being used.
  • Record who/what has access to an API key.
  • Rotate keys at least every 90 days.
  • Rotate keys when developers leave.
  • Rotate keys when they are leaked or compromised.
  • Create and deploy a new key before revoking the old one.
Dec 28, 2023

How do I manage API keys securely? ›

Best Practices to Secure API Keys
  1. Avoid Direct Storage in Code. ...
  2. Secure Storage Solutions. ...
  3. Regular Rotation and Deletion. ...
  4. Monitor and Limit Usage. ...
  5. Granular Access Control. ...
  6. Avoid Client-Side Exposure. ...
  7. Educate and Train Development Teams. ...
  8. Implementing Authorization & Authentication.
Oct 17, 2023

What are API keys and secrets? ›

Secret API keys serve as secure tokens to authenticate and authorize requests made to your API. They are deemed secret because their exposure to unauthorized individuals or the public could lead to security breaches.

What are the disadvantages of API keys? ›

Lack of user context: API keys do not provide user-specific authentication, making it challenging to track and manage individual user access. This limitation can be problematic in scenarios where user-level authorization is required.

How often should API keys be rotated? ›

Constantly rotate API keys to reduce potential vulnerabilities if exposed. Create a security policy that requires changing API keys every 30, 60 or 90 days. Many compliance regulations and frameworks, such as ISO 27001, require regular key rotation.

How often should keys be rotated? ›

Automatic key rotation at a defined period, such as every 90 days, increases security with minimal administrative complexity. You should also manually rotate a key if you suspect that it has been compromised, or when security guidelines require you to migrate an application to a stronger key algorithm.

Should API keys be encrypted? ›

Storing API keys directly in your database is bad practice and not secure. They should be hashed and/or encrypted first before being stored.

Which is the most secure method to transmit an API key? ›

Always use TLS

Every web API should use TLS (Transport Layer Security). TLS protects the information your API sends (and the information that users send to your API) by encrypting your messages while they're in transit. You might know TLS by its predecessor's name, SSL.

What is an API key example? ›

The API key string is an encrypted string, for example, AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe .

What happens if an API key is compromised? ›

If you suspect that your API key may be compromised, we recommend revoking the key immediately. You can do so by logging into your Anthropic account, going to the API keys page from your profile, clicking the meatball menu (i.e. the three horizontal dots) next to the key in question, and selecting 'Delete API Key. '

Should API keys be treated like passwords? ›

Tips For Using API keys

Avoid embedding API keys in code: Keys should be treated like passwords. They should never be hard-coded into your applications or committed to version control systems. If you must store them somewhere, use a secure location not accessible to the public.

Should I store API keys in database? ›

Storing API keys directly in your code is generally not recommended due to the potential security risks. If your code is ever shared or becomes publicly accessible, anyone who sees the API key can use it, potentially leading to abuse or a security breach.

What is the best practice for key rotation policy? ›

The best practice is to rotate your keys regularly. Choose a rotation interval between one and 12 months for your root key based on your security needs. After you set a rotation policy for a root key, the clock starts immediately based on the initial creation date for the key.

What is the best practice API timeout? ›

Best practices to avoid API gateway timeout
  • Proper caching strategy. ...
  • Set requests throttle and rate limit. ...
  • Use asynchronous processing. ...
  • Error handling and retry management. ...
  • Implement circuit breaker pattern. ...
  • Synthetic monitoring and alerting. ...
  • Concurrent requests management. ...
  • Cache responses.

What is the key rotation procedure? ›

Key rotation in asymmetric encryption involves the following steps:
  1. Step 1: Generate a new key pair. ...
  2. Step 2: Sign the new public key with the old private key. ...
  3. Step 3: Update systems with the new key pair. ...
  4. Step 5: Revoke and delete the old public key.
May 26, 2023

How long is the API key best practices? ›

API Key Best Practices

Key Length: An API key is generally more secure if it is longer. You can consider using a key length of about 32 characters, as it is more difficult for attackers to guess. Rate Limiting: Rate limiting can help to prevent the abuse of your API.

Top Articles
How Much Is a Paid Partnership on Instagram? - Lionize
How much The Paddington Bear 50p is worth - Skint Dad
Skigebiet Portillo - Skiurlaub - Skifahren - Testberichte
Dairy Queen Lobby Hours
Terrorist Usually Avoid Tourist Locations
Black Gelato Strain Allbud
Naturalization Ceremonies Can I Pick Up Citizenship Certificate Before Ceremony
27 Places With The Absolute Best Pizza In NYC
Best Theia Builds (Talent | Skill Order | Pairing + Pets) In Call of Dragons - AllClash
Hover Racer Drive Watchdocumentaries
Myql Loan Login
Miami Valley Hospital Central Scheduling
Mission Impossible 7 Showtimes Near Regal Bridgeport Village
Theycallmemissblue
What Time Chase Close Saturday
Truck Toppers For Sale Craigslist
Rainfall Map Oklahoma
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis - NFL
The Superhuman Guide to Twitter Advanced Search: 23 Hidden Ways to Use Advanced Search for Marketing and Sales
24 Best Things To Do in Great Yarmouth Norfolk
Sport-News heute – Schweiz & International | aktuell im Ticker
Urban Dictionary: hungolomghononoloughongous
Transfer and Pay with Wells Fargo Online®
Libinick
Aldi Bruce B Downs
Isaidup
Soulstone Survivors Igg
Baja Boats For Sale On Craigslist
Doki The Banker
Saxies Lake Worth
Is Henry Dicarlo Leaving Ktla
2004 Honda Odyssey Firing Order
Chelsea Hardie Leaked
Will there be a The Tower season 4? Latest news and speculation
Duke University Transcript Request
Japanese Emoticons Stars
Happy Shuttle Cancun Review
Tokioof
140000 Kilometers To Miles
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Cross-Border Share Swaps Made Easier Through Amendments to India’s Foreign Exchange Regulations - Transatlantic Law International
Improving curriculum alignment and achieving learning goals by making the curriculum visible | Semantic Scholar
Tattoo Shops In Ocean City Nj
Sarahbustani Boobs
Professors Helpers Abbreviation
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
From Grindr to Scruff: The best dating apps for gay, bi, and queer men in 2024
Boyfriends Extra Chapter 6
Nurses May Be Entitled to Overtime Despite Yearly Salary
Prologistix Ein Number
Unit 4 + 2 - Concrete and Clay: The Complete Recordings 1964-1969 - Album Review
Heisenberg Breaking Bad Wiki
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6160

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.