information-leakage-hardcoded-secrets-ai-code
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".
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 yoRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.