Interlace ESLint
ESLint Interlace
Secure CodingRules

no-hardcoded-credentials

Detects hardcoded passwords, API keys, tokens, and other sensitive credentials in source code. This rule is part of [`eslint-plugin-secure-coding`](https://www.

Keywords: hardcoded credentials, CWE-798, security, ESLint rule, API keys, passwords, tokens, secrets, environment variables, secret management, OWASP, credential security, auto-fix, LLM-optimized, code security

Detects hardcoded passwords, API keys, tokens, and other sensitive credentials in source code. This rule is part of eslint-plugin-secure-coding and provides LLM-optimized error messages that AI assistants can automatically fix.

⚠️ This rule warns by default in the recommended config.

Quick Summary

AspectDetails
CWE ReferenceCWE-798 (Use of Hard-coded Credentials)
SeverityCritical (security vulnerability)
Auto-Fix✅ Yes (suggests environment variables or secret managers)
CategorySecurity
ESLint MCP✅ Optimized for ESLint MCP integration
Best ForAll applications handling sensitive data, API integrations, database connections

Vulnerability and Risk

Vulnerability: Embedding sensitive credentials (like passwords, API keys, or database connection strings) directly in the source code.

Risk: This leads to credential exposure in version control systems, making them accessible to any developer with repository access or attackers if the code is leaked. It also makes credential rotation difficult and error-prone.

Error Message Format

The rule provides LLM-optimized error messages (Compact 2-line format) with actionable security guidance:

🔒 CWE-798 OWASP:A04 CVSS:9.8 | Hardcoded Credentials detected | CRITICAL [SOC2,PCI-DSS,HIPAA,GDPR,ISO27001,NIST-CSF]
   Fix: Review and apply the recommended fix | https://owasp.org/Top10/A04_2021/

Message Components

ComponentPurposeExample
Risk StandardsSecurity benchmarksCWE-798 OWASP:A04 CVSS:9.8
Issue DescriptionSpecific vulnerabilityHardcoded Credentials detected
Severity & ComplianceImpact assessmentCRITICAL [SOC2,PCI-DSS,HIPAA,GDPR,ISO27001,NIST-CSF]
Fix InstructionActionable remediationFollow the remediation steps below
Technical TruthOfficial referenceOWASP Top 10

Rule Details

Hardcoded credentials are one of the most common security vulnerabilities. This rule detects passwords, API keys, tokens, and other sensitive values that are directly embedded in source code, which can be exposed in version control systems.

Why This Matters

IssueImpactSolution
🔒 SecurityCredentials exposed in git historyUse environment variables
🐛 Data BreachAPI keys can be stolen from codeSecret management services
🔐 Access ControlPasswords visible to all developersAWS Secrets Manager, Vault
📊 ComplianceViolates security best practicesCI/CD secret injection

Detection Patterns

The rule detects:

  • API Keys: Stripe keys (sk_live_FAKE_KEY_FOR_TESTING), GitHub tokens (ghp_...), AWS keys (AKIA...)
  • JWT Tokens: Base64-encoded tokens with three parts
  • OAuth Tokens: GitHub, GitLab, and similar OAuth tokens
  • Passwords: Common weak passwords (password, admin, 123456)
  • Database Strings: Connection strings with embedded credentials
  • Secret Keys: Long base64 or hex strings (32+ characters)

Examples

❌ Incorrect

// Hardcoded API key
const apiKey = 'sk_live_FAKE_LIVE_KEY_FOR_TESTING_PURPOSES_ONLY_1234567890';

// Hardcoded password
const password = 'admin123';

// Hardcoded JWT token
const token =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

// Database connection string with credentials
const dbUrl = 'mysql://user:password@localhost:3306/dbname';

// AWS access key
const awsKey = 'AKIAIOSFODNN7EXAMPLE';

✅ Correct

// Environment variable
const apiKey = process.env.API_KEY;

// Secret manager
const password = await getSecret('database-password');

// Configuration service
const token = configService.get('JWT_TOKEN');

// Environment variable for database
const dbUrl = process.env.DATABASE_URL;

// AWS SDK with IAM roles (no keys needed)
const s3 = new AWS.S3(); // Uses IAM role

Configuration

{
  rules: {
    'secure-coding/no-hardcoded-credentials': ['error', {
      ignorePatterns: ['^test-'],           // Ignore test credentials
      allowInTests: false,                  // Allow in test files
      minLength: 8,                         // Minimum credential length
      detectApiKeys: true,                  // Detect API keys
      detectPasswords: true,                // Detect passwords
      detectTokens: true,                   // Detect tokens
      detectDatabaseStrings: true          // Detect database strings
    }]
  }
}

Options

OptionTypeDefaultDescription
ignorePatternsstring[][]Regex patterns to ignore (e.g., ['^test-'] for test keys)
allowInTestsbooleanfalseAllow credentials in test files (.test.ts, .spec.ts)
minLengthnumber8Minimum length for credential detection (except common passwords)
detectApiKeysbooleantrueDetect API keys (Stripe, AWS, etc.)
detectPasswordsbooleantrueDetect common weak passwords
detectTokensbooleantrueDetect JWT and OAuth tokens
detectDatabaseStringsbooleantrueDetect database connection strings with credentials

Ignoring Test Credentials

{
  rules: {
    'secure-coding/no-hardcoded-credentials': ['error', {
      ignorePatterns: ['^test-', '^mock-', '^fake-']
    }]
  }
}

Allowing Credentials in Test Files

{
  rules: {
    'secure-coding/no-hardcoded-credentials': ['error', {
      allowInTests: true  // Allows credentials in .test.ts and .spec.ts files
    }]
  }
}

Rule Logic Flow

Best Practices

1. Use Environment Variables

// ✅ Good
const apiKey = process.env.STRIPE_API_KEY;
if (!apiKey) {
  throw new Error('STRIPE_API_KEY is required');
}

2. Use Secret Management Services

// ✅ Good - AWS Secrets Manager
import { SecretsManager } from '@aws-sdk/client-secrets-manager';

const client = new SecretsManager({ region: 'us-east-1' });
const secret = await client.getSecretValue({ SecretId: 'api-keys' });
const apiKey = JSON.parse(secret.SecretString).stripeKey;

3. Use Configuration Services

// ✅ Good - Config service
import { ConfigService } from '@nestjs/config';

@Injectable()
export class ApiService {
  constructor(private config: ConfigService) {}

  getApiKey() {
    return this.config.get<string>('API_KEY');
  }
}

4. Never Commit Credentials

# ✅ Good - Use .env files (gitignored)
echo "API_KEY=sk_live_FAKE_KEY_FOR_TESTING" >> .env
echo ".env" >> .gitignore

Known False Negatives

The following patterns are not detected due to static analysis limitations:

Credentials from Config

Why: Config values not traced.

// ❌ NOT DETECTED - From config
const password = config.dbPassword;

Mitigation: Use proper secrets management.

Environment Variables

Why: Env var content not analyzed.

// ❌ NOT DETECTED - Env var
const secret = process.env.API_KEY;

Mitigation: Never hardcode or expose secrets.

Dynamic Credential Access

Why: Dynamic property access not traced.

// ❌ NOT DETECTED - Dynamic
const cred = credentials[type];

Mitigation: Audit all credential access patterns.

Resources

Version History

  • 1.3.0 - Initial release with comprehensive credential detection patterns

On this page