Avoid Hardcoded Secrets
Detects hardcoded secrets, API keys, and tokens in the source code.
Avoid Hardcoded Secrets
Rule ID: avoid_hardcoded_secrets
Severity: 🔴 High
Category: Secrets (OWASP M1)
Description
This rule scans string literals for patterns that resemble API keys, authentication tokens, passwords, and other sensitive credentials. Hardcoding secrets in source code is a major security vulnerability, as it exposes these credentials to anyone with access to the code (including public repositories) and makes it impossible to rotate secrets without redeploying the application.
Non-Compliant Code
Hardcoding an API key:
class PaymentService {
// ❌ BAD: Secret is hardcoded
final String stripeKey = 'sk_live_51Mz...';
}
Compliant Code
Load the secret from a secure source at runtime:
class PaymentService {
// ✅ GOOD: Secret is injected
final String stripeKey;
PaymentService({required this.stripeKey});
}
// Load from secure storage or build environment
final key = await SecureStorage.get('STRIPE_KEY');
How to Fix
- Remove the Secret: Delete the hardcoded string immediately.
- Rotate the Credential: If the secret was committed to version control, consider it compromised. Revoke it and generate a new one.
- Use Environment Variables: For server-side Dart, use environment variables.
- Use Secure Storage: For mobile apps, store sensitive user tokens in secure storage (e.g.,
flutter_secure_storage). - Backend Proxy: For third-party API keys that cannot be exposed to the client, move the logic to a backend server. The mobile app should call your backend, which then attaches the key and calls the third-party service.
1. Credential Exposure
Source code is often widely shared within a team or even publicly. Hardcoded secrets give anyone with read access to the repository full access to the associated services.
2. Reverse Engineering
Even in compiled mobile apps, strings are often stored in cleartext in the binary. Attackers can decompile the app and extract the keys.
3. Operational Difficulty
Rotating a compromised hardcoded key requires a full app update and release cycle.
When to Ignore
This rule uses pattern matching and entropy analysis, which can sometimes produce false positives. You can ignore this rule if:
- The string is not a secret: It might be a public ID, a hash, or a long random string used for non-security purposes.
- The key is public by design: Some "keys" (like Firebase
API_KEYor Stripe publishable keys) are meant to be public. However, verify the documentation for that specific service before ignoring.
Always ensure that ignoring this rule does not introduce a security vulnerability in your specific use case.