Claude
Skills
Sign in
Back

information-leakage-hardcoded-secrets-ai-code

Included with Lifetime
$97 forever

Understand how AI-generated code exposes sensitive information through hardcoded credentials and verbose logging. Use this skill when you need to learn about hardcoded secrets in AI code, understand logging vulnerabilities, recognize exposed API keys, or prevent information disclosure. Triggers include "hardcoded credentials", "hardcoded secrets", "API keys in code", "information leakage", "verbose logging", "exposed secrets", "AWS keys", "logging vulnerabilities", "sensitive data logs".

Backend & APIs

What this skill does


# Sensitive Information Exposure in AI-Generated Code

## The Pervasiveness of Hardcoded Secrets

A comprehensive analysis by WebProNews found:

> "AI models trained on public repositories frequently suggest hardcoding API keys and credentials, as these patterns appear millions of times in their training data."

The problem is exacerbated by the fact that many developers using vibe coding are non-technical and unaware of the security implications.

## 1.3.1 Hardcoded Credentials

### The Real-World Incident

Research from Analytics India Magazine documented a real-world incident:

> "A developer used Cursor to build a SaaS app and accidentally committed hardcoded AWS credentials. Within days, attackers had discovered the exposed keys and racked up **thousands of dollars in charges**."

This is not theoretical—it's happening regularly.

### AI-Generated Vulnerable Code

```python
# Prompt: "Connect to AWS S3 and upload files"
import boto3
import stripe
import requests

class CloudStorage:
    def __init__(self):
        # ❌ CRITICAL: Hardcoded AWS credentials
        self.aws_key = "AKIAIOSFODNN7EXAMPLE"
        self.aws_secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

        # ❌ CRITICAL: Hardcoded API keys
        self.stripe_key = "sk_live_EXAMPLE_DO_NOT_USE_HARDCODED_KEYS"
        self.sendgrid_key = "SG.EXAMPLE_KEY_DO_NOT_HARDCODE"

        # ❌ CRITICAL: Database credentials in code
        self.db_config = {
            'host': 'prod-db.company.com',
            'user': 'admin',
            'password': 'SuperSecretPass123!',
            'database': 'production'
        }

    def upload_to_s3(self, file_path, bucket_name):
        # ❌ VULNERABLE: Using hardcoded credentials
        s3 = boto3.client(
            's3',
            aws_access_key_id=self.aws_key,
            aws_secret_access_key=self.aws_secret
        )
        s3.upload_file(file_path, bucket_name, file_path)

# Prompt: "Send API request with authentication"
def fetch_user_data(user_id):
    # ❌ VULNERABLE: API key in URL
    response = requests.get(
        f"https://api.service.com/users/{user_id}?api_key=abc123def456"
    )
    return response.json()
```

### Why This Is Critically Dangerous

**1. Committed to Version Control:**
- Code pushed to GitHub/GitLab
- Secrets now in git history forever
- Even if removed in later commit, still in history
- Public repos = instant compromise
- Private repos = compromised if repo breached

**2. Bots Scan for Exposed Secrets:**
- Automated bots scan GitHub 24/7
- Find exposed AWS keys within **minutes**
- Immediately start using them
- Rack up charges before you notice

**3. Difficult to Rotate:**
- Once exposed, must rotate all keys
- May require updating multiple services
- Downtime during rotation
- Some keys can't be rotated easily

### Secure Implementation

```python
import os
import boto3
import stripe
from dotenv import load_dotenv
from aws_secretsmanager import get_secret
import logging

# ✅ SECURE: Load environment variables from .env file (not in version control)
load_dotenv()

class CloudStorageSecure:
    def __init__(self):
        # ✅ SECURE: Retrieve credentials from environment variables
        self.aws_key = os.getenv('AWS_ACCESS_KEY_ID')
        self.aws_secret = os.getenv('AWS_SECRET_ACCESS_KEY')

        # ✅ SECURE: Use AWS Secrets Manager for production
        if os.getenv('ENVIRONMENT') == 'production':
            secrets = self._get_secrets_from_aws()
            self.stripe_key = secrets['stripe_key']
            self.sendgrid_key = secrets['sendgrid_key']
        else:
            self.stripe_key = os.getenv('STRIPE_KEY')
            self.sendgrid_key = os.getenv('SENDGRID_KEY')

        # ✅ SECURE: Database connection from environment
        self.db_config = {
            'host': os.getenv('DB_HOST'),
            'user': os.getenv('DB_USER'),
            'password': os.getenv('DB_PASSWORD'),
            'database': os.getenv('DB_NAME'),
            'ssl_ca': os.getenv('DB_SSL_CA'),  # SSL for production
            'ssl_verify_cert': True
        }

        # ✅ SECURE: Validate all credentials are present
        self._validate_configuration()

    def _get_secrets_from_aws(self):
        """Retrieve secrets from AWS Secrets Manager"""
        session = boto3.session.Session()
        client = session.client(service_name='secretsmanager')

        try:
            response = client.get_secret_value(SecretId='prod/api-keys')
            return json.loads(response['SecretString'])
        except Exception as e:
            logging.error(f"Failed to retrieve secrets: {e}")
            raise

    def _validate_configuration(self):
        """Ensure all required configuration is present"""
        required_vars = [
            'aws_key', 'aws_secret', 'stripe_key',
            'sendgrid_key', 'db_config'
        ]

        for var in required_vars:
            if not getattr(self, var, None):
                raise ValueError(f"Missing required configuration: {var}")

    def upload_to_s3(self, file_path, bucket_name):
        # ✅ SECURE: Use IAM roles in production instead of keys
        if os.getenv('ENVIRONMENT') == 'production':
            s3 = boto3.client('s3')  # Uses IAM role
        else:
            s3 = boto3.client(
                's3',
                aws_access_key_id=self.aws_key,
                aws_secret_access_key=self.aws_secret
            )

        # ✅ SECURE: Add encryption and access logging
        s3.upload_file(
            file_path,
            bucket_name,
            file_path,
            ExtraArgs={
                'ServerSideEncryption': 'AES256',
                'Metadata': {
                    'uploaded_by': os.getenv('APP_NAME', 'unknown'),
                    'upload_time': str(datetime.utcnow())
                }
            }
        )

def fetch_user_data_secure(user_id):
    # ✅ SECURE: Use headers for API authentication
    headers = {
        'Authorization': f"Bearer {os.getenv('API_TOKEN')}",
        'X-API-Key': os.getenv('API_KEY'),
        'X-Request-ID': str(uuid.uuid4())  # For tracking
    }

    # ✅ SECURE: Never put secrets in URLs
    response = requests.get(
        f"https://api.service.com/users/{user_id}",
        headers=headers,
        timeout=10  # Always set timeouts
    )

    # ✅ SECURE: Log requests without exposing secrets
    logging.info(f"API request to /users/{user_id} - Status: {response.status_code}")

    return response.json()
```

### Why AI Hardcodes Credentials

**1. Prevalence in Training Data:**
- Millions of code examples on GitHub with hardcoded keys
- Tutorial code uses placeholder keys for simplicity
- AI learns this as "normal" pattern

**2. Simplicity:**
- Hardcoding is fewer lines of code
- No need to explain environment variables
- "Works" immediately in example

**3. Context Blindness:**
- AI doesn't distinguish between:
  - Example/tutorial code (hardcoded OK)
  - Production code (hardcoded NEVER OK)
- Treats all prompts the same way

### Where AI Hardcodes Secrets

**1. Direct Variable Assignment:**
```python
API_KEY = "sk_live_abc123def456"
AWS_SECRET = "wJalrXUtn..."
DATABASE_PASSWORD = "SuperSecret123!"
```

**2. In Configuration Objects:**
```javascript
const config = {
  stripeKey: 'sk_live_...',
  dbPassword: 'password123'
};
```

**3. In URLs:**
```javascript
fetch(`https://api.example.com/data?key=abc123def456`)
```

**4. In Connection Strings:**
```python
conn = mysql.connector.connect(
    host='prod.db.com',
    user='admin',
    password='SuperSecret123!'
)
```

### Attack Timeline

**T+0 minutes:** Developer commits code with hardcoded AWS keys
**T+5 minutes:** Bots detect exposed keys, begin using
**T+30 minutes:** $500 in unauthorized EC2 instances spun up
**T+2 hours:** Developer notices unusual AWS bill
**T+4 hours:** $10,000 in charges, keys finally rotated
**T+1 week:** Final bill: $50,000+

**This is a real timeline from documented incidents.**

### How to Find Hardcoded Secrets

**Scan yo

Related in Backend & APIs