Claude skill secret exposure security — SA-SKL-SECRETEXPOSE
Secrets — API keys, database credentials, JWT signing keys, Stripe live-mode tokens — are the highest-value targets in an MCP skill deployment. They are also routinely mishandled in four distinct ways that SkillAudit finds consistently: a misconfigured static file server exposes the .env file over HTTP, a hardcoded key survives a git push despite scanning tools, an Axios error handler echoes the full err.config (including the Authorization header) back to the client, and a startup debug log dumps the entire process.env to stdout on every cold start. SECRETEXPOSE-001 through SECRETEXPOSE-004 cover each with the exact vulnerable pattern and an auditable fix.
Why secret exposure is a first-priority audit category for MCP skills
An MCP skill typically aggregates access to multiple upstream services — a database, a payment processor, a code-hosting API, an AI inference endpoint. Each of those integrations requires a credential. The skill's deployment surface is therefore a concentration point for high-value secrets that, if exposed, can compromise services well beyond the skill itself. A leaked Stripe live-mode key enables unauthorized charges. A leaked GitHub token enables repository access or CI/CD pipeline manipulation. A leaked database URL with embedded credentials enables direct data access that bypasses all application-layer authorization controls. Secret exposure vulnerabilities are particularly insidious because they are often introduced by a single developer action — a misplaced file, a debug log statement, a convenient shortcut — and they may remain undetected for months until a scan or an incident surfaces them.
SA-SKL-SECRETEXPOSE in scope: SECRETEXPOSE-001 (.env served by Express static), SECRETEXPOSE-002 (API key hardcoded in git-committed source), SECRETEXPOSE-003 (Axios error config leaks Authorization header to client), SECRETEXPOSE-004 (process.env dumped to stdout on startup). Each includes SkillAudit detection rules, pre-commit scanning configuration, and safe error-handling helpers ready to drop into an Express MCP skill.
SECRETEXPOSE-001 — .env file served by misconfigured static middleware
Express's express.static() middleware serves every file in the specified directory by default, including dotfiles. When a developer sets up an MCP skill project, the application root typically contains a .env file with all secrets in plaintext. If the static root is set to '.', 'public' without verifying the directory tree, or the .env is accidentally created or symlinked inside the static root, a simple GET /.env request returns all secrets in plaintext. Shodan and Censys actively probe for this pattern — automated scanners test /.env, /.env.local, /.env.production on every newly indexed server. The window between deployment and exploit can be minutes. The fix requires three layers: explicit dotfiles deny in Express, a Caddy respond rule, and a periodic audit confirming no .env* files exist under any static-servable path.
// VULNERABLE: express.static serves dotfiles by default, including .env
const express = require('express');
const app = express();
// If .env is at ./public/.env, or if static root is set to '.':
app.use(express.static('public'));
// VULNERABLE: GET /public/.env → returns DATABASE_URL=postgres://...
// VULNERABLE: express.static('.') → GET /.env returns all secrets
// Another common mistake: accidentally serving the project root
app.use('/static', express.static(__dirname));
// VULNERABLE: GET /static/.env returns plaintext secrets
// GET /static/.env.local
// GET /static/.env.production
// FIXED: three-layer defence — Express dotfiles deny, Caddy block, filesystem audit
// Layer 1: Express — deny dotfiles explicitly
app.use(express.static('public', {
dotfiles: 'deny', // Returns 403 for any file starting with '.'
// Also consider 'ignore' (404) — 'deny' (403) is more explicit and auditable
}));
// If you must serve from project root (avoid this — prefer a dedicated 'public/' dir):
app.use(express.static(__dirname, {
dotfiles: 'deny',
}));
// Layer 2: Caddy — block .env at reverse proxy level as defence-in-depth
// Caddyfile fragment:
// @dotenv {
// path /.env*
// }
// respond @dotenv 403
// Layer 3: filesystem audit — run in CI to verify no .env files are inside static dirs
// find public/ -name '.env*' -not -path './.git/*' | grep . && exit 1 || echo "OK"
// Layer 4: .gitignore — always present, belt-and-suspenders
// .env
// .env.*
// !.env.example
// Verification: confirm dotfiles: 'deny' is working in integration tests
// test('GET /.env returns 403', async () => {
// const res = await request(app).get('/.env');
// expect(res.status).toBe(403);
// });
express.static() without { dotfiles: 'deny' }; if a .env or .env.* file is present in or below the static root (through developer error, symlink, or deployment artifact), GET /.env returns all secrets in plaintext; automated Shodan/Censys probes test for this within minutes of deployment. Fix: set { dotfiles: 'deny' } in every express.static() call; add a Caddy respond /.env* 403 rule; run a CI check confirming no .env* files exist under any static-servable path. Detection: SkillAudit flags express.static() calls without the dotfiles: 'deny' option and scans for .env files co-located with static-servable directories.SECRETEXPOSE-002 — API key hardcoded in git-committed source
Hardcoded credentials in source code are the single most common secret-exposure pattern SkillAudit observes. The workflow is consistent: a developer is integrating a new upstream API (GitHub, Stripe, OpenAI, AWS), creates a test key, and hard-codes it temporarily as const GITHUB_TOKEN = 'ghp_xxxxxxxxxxxxxxxxxxx' to verify the integration. The intent is always to move it to process.env before merging, but the commit happens first. GitHub secret scanning fires immediately on push to a public repo — but in the interval between git push and key revocation, automated bots that watch for GitHub secret-scanning alerts harvest the token. Even after revocation, the token exists in git history and can be recovered with git log -S. The fix requires pre-commit scanning that prevents the secret from ever reaching a commit, combined with CI-level scanning as a backstop.
// VULNERABLE: API key hardcoded as string literal in source file
// Even if moved to process.env before merging, the commit is in git history forever
// src/integrations/github.js
const { Octokit } = require('@octokit/rest');
// VULNERABLE: hardcoded personal access token
const GITHUB_TOKEN = 'ghp_A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8';
const octokit = new Octokit({ auth: GITHUB_TOKEN });
// Also common patterns:
// const stripe = new Stripe('sk_live_4eC39HqLyjWDarjtT1zdp7dc');
// const openai = new OpenAI({ apiKey: 'sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' });
// const awsConfig = { accessKeyId: 'AKIAIOSFODNN7EXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' };
// FIXED: environment variables only; pre-commit scanning blocks accidental commits
// src/integrations/github.js — FIXED
const { Octokit } = require('@octokit/rest');
// All credentials from environment variables — never string literals
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
// Validate required env vars at startup — fail fast if missing
const REQUIRED_ENV = ['GITHUB_TOKEN', 'STRIPE_SECRET_KEY', 'DATABASE_URL', 'JWT_SECRET'];
for (const key of REQUIRED_ENV) {
if (!process.env[key]) {
// Throw at startup — do not log the value, only the key name
throw new Error(`Missing required environment variable: ${key}`);
}
}
// .env.example — commit this, not .env
// GITHUB_TOKEN=ghp_your_token_here
// STRIPE_SECRET_KEY=sk_live_your_key_here
// DATABASE_URL=postgres://user:pass@host/db
// JWT_SECRET=your_jwt_secret_here
// Pre-commit hook: .husky/pre-commit
// #!/bin/sh
// gitleaks detect --source . --no-git --redact
// # Fails commit if any secrets are detected
// .gitleaks.toml — add patterns for internal services
// [[rules]]
// id = "internal-api-key"
// description = "Internal SkillAudit API key"
// regex = '''sa_live_[a-zA-Z0-9]{32}'''
// severity = "CRITICAL"
// CI pipeline — gitleaks as backstop
// - name: Scan for secrets
// run: gitleaks detect --source . --redact --exit-code 1
ghp_, Stripe live key sk_live_, OpenAI key sk-proj-, AWS access key AKIA); even if the commit is not public, the secret persists in git history and is recoverable with git log -S; if ever pushed to a public repo, bots harvest it within minutes of the GitHub secret-scanning alert. Fix: use process.env exclusively for all credentials; install gitleaks as a pre-commit hook; add gitleaks detect to CI; rotate any key that was ever committed — revocation alone is insufficient because the history remains. Detection: SkillAudit scans for string literals matching 25+ secret patterns in source files and git diff output.SECRETEXPOSE-003 — Secret leaked in Axios error response body
MCP skills that call upstream services via Axios commonly add a global error interceptor to map errors to a standard response format. A naive implementation forwards the Axios error object or its config property to the client: res.status(500).json({ error: err.message, details: err.config }). The err.config object on an Axios error is the full request configuration that produced the error — it contains the request URL, method, all request headers (including Authorization: Bearer sk_live_...), and the request body. When an upstream API call fails (Stripe returning 429, GitHub returning 403, a database connection timing out), the interceptor fires, and the entire Axios config — including the live API key in the Authorization header — is returned to the client in the 500 response body. Any user who triggers an error on a third-party API call receives the skill's upstream credentials.
// VULNERABLE: Axios error config contains Authorization header — returned to client
const axios = require('axios');
const stripeClient = axios.create({
baseURL: 'https://api.stripe.com/v1',
headers: {
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
});
// VULNERABLE: global error interceptor leaks err.config to API client
app.post('/api/billing/charge', authMiddleware, async (req, res) => {
try {
const charge = await stripeClient.post('/charges', req.body);
res.json(charge.data);
} catch (err) {
// VULNERABLE: err.config includes { headers: { Authorization: 'Bearer sk_live_...' } }
// err.message includes the full request URL with query params
res.status(500).json({
error: err.message, // may include URL with API key
details: err.config, // VULNERABLE: full Axios request config
response: err.response?.data, // may include Stripe error with upstream details
});
}
});
// FIXED: classifyAxiosError() extracts safe fields — no headers, no config, no credentials
const axios = require('axios');
// Safe Axios error classifier — extracts only non-sensitive diagnostic fields
function classifyAxiosError(err) {
const safe = {
type: 'upstream_error',
// requestId for server-side log correlation — do not leak to client
};
if (err.response) {
// Upstream responded with an error status
safe.upstreamStatus = err.response.status;
safe.upstreamService = new URL(err.config?.url || 'http://x').hostname;
// Do NOT include: err.response.config, err.response.headers, err.config
} else if (err.request) {
// Request was made but no response received (timeout, network error)
safe.upstreamStatus = 'no_response';
} else {
// Setup error — config issue
safe.upstreamStatus = 'config_error';
}
return safe;
}
app.post('/api/billing/charge', authMiddleware, async (req, res) => {
const requestId = req.id; // set by express-request-id or similar
try {
const charge = await stripeClient.post('/charges', req.body);
res.json(charge.data);
} catch (err) {
// Log full error server-side with credentials redacted
logger.error({
requestId,
upstreamStatus: err.response?.status,
upstreamUrl: err.config?.url?.replace(/Bearer\s+\S+/, 'Bearer [REDACTED]'),
errMessage: err.message,
}, 'Stripe API error');
// Return only safe, non-credential fields to client
const safeError = classifyAxiosError(err);
res.status(502).json({
error: 'Upstream service error',
requestId, // allows correlation with server log without exposing details
...safeError,
});
}
});
err.config, err.request, or the full error object in the response body; Axios err.config includes headers.Authorization with the upstream API key used to make the request; any user who triggers a 500 error on a third-party API call receives the skill's live credentials. Fix: build a classifyAxiosError() helper that extracts only upstreamStatus and service hostname; log err.config server-side with credentials redacted; return only a stable error code and requestId to the client. Detection: SkillAudit flags catch blocks that pass err.config, err, or JSON.stringify(err) into res.json() or res.send().SECRETEXPOSE-004 — process.env dump via console.log on startup
A developer debugging a production deployment adds console.log('Starting up', process.env) near the top of server.js to verify that environment variables are being injected correctly by the container orchestrator. This is a reasonable debugging technique in a local environment where stdout is visible only to the developer. In production, stdout is captured by the container runtime (Docker, Kubernetes) and forwarded to a log aggregator. On every cold start — container restart, scaling event, rolling deployment — the entire process.env object is serialized to JSON and written to the log. It contains every environment variable that the container runtime injects: DATABASE_URL, JWT_SECRET, STRIPE_SECRET_KEY, GITHUB_TOKEN, and potentially dozens of internal service credentials. The developer forgets to remove the log statement before committing, and the production deployment emits a full credential dump to the log sink on every restart for weeks or months before discovery.
// VULNERABLE: process.env dump writes all secrets to stdout on every cold start
// server.js
require('dotenv').config();
const express = require('express');
const app = express();
// VULNERABLE: logs ALL environment variables on startup
// In production, this includes DATABASE_URL, JWT_SECRET, STRIPE_SECRET_KEY, GITHUB_TOKEN, etc.
console.log('Starting up', process.env);
// Also common:
// console.log('Config:', JSON.stringify(process.env, null, 2));
// logger.debug('Environment:', process.env);
// console.log('DB URL:', process.env.DATABASE_URL); // at least this only leaks one secret
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
// FIXED: validate required vars without logging values; log only safe diagnostic keys
require('dotenv').config();
const express = require('express');
const app = express();
// 1. Validate required env vars at startup — fail fast, never log values
const REQUIRED_VARS = ['DATABASE_URL', 'JWT_SECRET', 'STRIPE_SECRET_KEY', 'GITHUB_TOKEN'];
const missing = REQUIRED_VARS.filter(k => !process.env[k]);
if (missing.length > 0) {
// Log key names only — never values
console.error('Missing required environment variables:', missing.join(', '));
process.exit(1);
}
// 2. Log only non-secret startup diagnostics
const SAFE_DIAGNOSTIC_KEYS = ['NODE_ENV', 'PORT', 'LOG_LEVEL', 'REGION', 'SERVICE_NAME'];
const startupDiagnostics = {};
for (const key of SAFE_DIAGNOSTIC_KEYS) {
if (process.env[key] !== undefined) startupDiagnostics[key] = process.env[key];
}
console.log('Startup diagnostics:', JSON.stringify(startupDiagnostics));
// Output: Startup diagnostics: {"NODE_ENV":"production","PORT":"3000","LOG_LEVEL":"info"}
// 3. ESLint rule to catch process.env log statements:
// "no-restricted-syntax": ["error", {
// "selector": "CallExpression[arguments] > MemberExpression[object.name='process'][property.name='env']",
// "message": "Do not log process.env directly — log only specific non-secret keys"
// }]
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
process.env directly via console.log, logger.*, or JSON.stringify(process.env); on every cold start (container restart, scaling event, deployment), all environment variables — database credentials, JWT secrets, API keys — are written to stdout and forwarded to log sinks where they may be retained for months; any party with log-read access obtains the full credential set. Fix: validate required env vars at startup by checking presence without logging values; log only a curated safe-key list (NODE_ENV, PORT, LOG_LEVEL); add an ESLint rule banning process.env in log call arguments. Detection: SkillAudit flags console.log(process.env), logger.*(process.env), and JSON.stringify(process.env) patterns in startup and configuration files.SkillAudit detection summary — SA-SKL-SECRETEXPOSE
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| SECRETEXPOSE-001 | HIGH | express.static() calls without { dotfiles: 'deny' }; .env* files co-located with static-servable directories | dotfiles: 'deny' option; Caddy respond /.env* 403; CI filesystem audit |
| SECRETEXPOSE-002 | HIGH | String literals matching secret patterns (ghp_, sk_live_, AKIA, sk-proj-) in source files or git diff | process.env for all credentials; gitleaks pre-commit hook; CI scan; rotate committed keys |
| SECRETEXPOSE-003 | HIGH | Catch blocks passing err.config, err, or JSON.stringify(err) into res.json() or res.send() | classifyAxiosError() helper; log full error server-side; return only requestId and stable error code to client |
| SECRETEXPOSE-004 | MEDIUM | console.log(process.env), logger.*(process.env), JSON.stringify(process.env) in startup or config files | Validate required vars by presence check; log only safe diagnostic key list; ESLint rule |
Related patterns: For credentials and tokens written to log files via request body logging, see SA-SKL-LOGINJECT. For sensitive data disclosed in stack traces and verbose error responses, see SA-SKL-INFODISCLOSURE. For file access vulnerabilities that allow reading .env files via path traversal, see SA-SKL-FILEACCESS.