Why is this an issue?

Hard-coding secrets in source code or binaries makes it easy for attackers to extract sensitive information, especially in distributed or open-source applications. This practice exposes credentials and tokens, increasing the risk of unauthorized access and data breaches.

This rule detects variables/fields having a name matching a list of words (secret, token, credential, auth, api[_.-]?key) being assigned a pseudorandom hard-coded value. The pseudorandomness of the hard-coded value is based on its entropy and the probability to be human-readable. The randomness sensibility can be adjusted if needed. Lower values will detect less random values, raising potentially more false positives.

How to fix it

Secrets should be stored in a configuration file that is not committed to the code repository, in a database, or managed by your cloud provider’s secrets management service. If a secret is exposed in the source code, it must be rotated immediately.

Code Examples

Noncompliant code example

import requests

API_KEY = "1234567890abcdef"  # Hard-coded secret (bad practice)

def send_api_request(data):
    headers = {
        "Authorization": f"Bearer {API_KEY}"
    }
    return requests.post("https://api.example.com", headers=headers, data=data)

Compliant solution

Using AWS Secrets Manager:

import boto3
import logging

SECRET_NAME = "MY_API_KEY"

client = boto3.client("secretsmanager")
secret = client.get_secret_value(SecretId=SECRET_NAME)

def send_api_request(data):
    headers = {
        "Authorization ": f"Bearer {secret}"
    }
    return requests.post("https://api.example.com", headers=headers, data=data)

Using Azure Key Vault Secret:

import os
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential

SECRET_NAME = "MY_API_KEY"

keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = f"https://{keyVaultName}.vault.azure.net"

credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
secret = client.get_secret(SECRET_NAME)

def send_api_request(data):
    headers = {
        "Authorization ": f"Bearer {secret.value}"
    }
    return requests.post("https://api.example.com", headers=headers, data=data)

Resources