All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S6418.html Maven / Gradle / Ivy

The newest version!

Because it is easy to extract strings from an application source code or binary, secrets should not be hard-coded. This is particularly true for applications that are distributed or that are open-source.

In the past, it has led to the following vulnerabilities:

Secrets should be stored outside of the source code in a configuration file or a management service for secrets.

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.

Ask Yourself Whether

  • The secret allows access to a sensitive component like a database, a file storage, an API, or a service.
  • The secret is used in a production environment.
  • Application re-distribution is required before updating the secret.

There would be a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the secret in a configuration file that is not pushed to the code repository.
  • Use your cloud provider’s service for managing secrets.
  • If a secret has been disclosed through the source code: revoke it and create a new one.

Sensitive 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)

See





© 2015 - 2025 Weber Informatics LLC | Privacy Policy