Skip to content

Security: neverinfamous/db-mcp

SECURITY.md

πŸ”’ Security Guide

The db-mcp SQLite MCP server implements comprehensive security measures to protect your databases across both WASM and Native backends.

πŸ›‘οΈ Database Security

Dual SQLite Architecture

db-mcp offers two backend options β€” both with layered security:

  • βœ… WASM (sql.js) β€” runs in-process with zero native dependencies; 115 tools
  • βœ… Native (better-sqlite3) β€” full-featured with native bindings; 139 tools

PRAGMA Hardening

Both backends apply security-relevant PRAGMAs on initialization:

  • βœ… PRAGMA foreign_keys = ON β€” enforces referential integrity and ON DELETE CASCADE
  • βœ… PRAGMA journal_mode = WAL β€” auto-enabled for file-based databases (high concurrency, non-blocking reads)
  • βœ… PRAGMA busy_timeout β€” configurable wait to avoid SQLITE_BUSY errors under contention
  • βœ… Parameterized queries β€” all user input bound via ? placeholders

File Permissions (Docker)

  • βœ… Data directory: 700 (full access for owner only) in Docker
  • βœ… Non-root user (appuser:appgroup) owns data directory

πŸ” Input Validation

SQL Injection Prevention

  • βœ… Parameterized queries used throughout β€” never string interpolation
  • βœ… Input validation via Zod schemas before database operations
  • βœ… WHERE clause validation with 10 dangerous pattern detections:
    • Subquery injection (SELECT inside WHERE)
    • Statement termination (;)
    • SQL comments (--, /*)
    • UNION injection (UNION SELECT)
    • Extension loading (load_extension())
    • Database attachment (ATTACH DATABASE)
    • PRAGMA injection
    • File I/O (writefile(), readfile())
    • Tokenizer exploitation (fts3_tokenizer())
    • Hex blob injection (X'...')
  • βœ… Identifier sanitization β€” table, column, and index names validated against injection
  • βœ… FTS5 / LIKE pattern sanitization β€” escapes %, _, \ wildcards

Structured Error Handling

Every tool returns structured error responses β€” never raw exceptions or internal details:

{
  "success": false,
  "error": "Descriptive message with context",
  "code": "MODULE_ERROR_CODE",
  "category": "VALIDATION_ERROR",
  "suggestion": "Actionable remediation hint",
  "recoverable": true
}

Error codes are module-prefixed (e.g., JSON_PARSE_FAILED, VECTOR_DIMENSION_MISMATCH). Internal stack traces are logged server-side but never exposed to clients.

πŸ§ͺ Code Mode Sandbox Security

Code Mode (sqlite_execute_code) runs user-supplied JavaScript in a secure sandbox:

Isolation Modes

Mode Environment Variable Security Level
Worker (default) CODEMODE_ISOLATION=worker Enhanced β€” worker_threads with MessagePort RPC
VM CODEMODE_ISOLATION=vm Standard β€” node:vm context isolation

Sandbox Restrictions

  • βœ… No filesystem access β€” fs, path, child_process are unavailable
  • βœ… No network access β€” fetch, http, net modules are unavailable
  • βœ… No global mutation β€” setTimeout, setInterval, process, require are removed from the sandbox context
  • βœ… Execution timeout β€” 30-second hard limit per execution (configurable, max 30s)
  • βœ… Idle timeout β€” sandbox instances auto-dispose after 60 seconds of inactivity
  • βœ… MessagePort RPC bridge β€” in Worker mode, API calls cross a serialization boundary; no shared memory

API Surface

Code Mode exposes only the typed sqlite.* SDK β€” agents can compose queries and chain operations but cannot escape the sandbox boundary.

🌐 HTTP Transport Security

When running in HTTP mode (--transport http), the following security measures apply:

CORS Configuration

  • βœ… Configurable origins via --cors-origins flag (comma-separated)
  • βœ… Wildcard subdomain matching (e.g., *.example.com matches app.example.com)
  • ⚠️ Default: * (allow all origins) for backward compatibility
  • πŸ”’ Recommended: Set specific origins for production deployments
# Restrict CORS to specific origins
db-mcp --transport http --cors-origins "http://localhost:3000,https://my-app.com"

Security Headers & Protections

  • βœ… DNS Rebinding Protection β€” localhostHostValidation middleware from MCP SDK
  • βœ… Strict-Transport-Security (HSTS) β€” max-age=31536000; includeSubDomains (opt-in via --enable-hsts)
  • βœ… X-Content-Type-Options: nosniff β€” prevents MIME sniffing
  • βœ… X-Frame-Options: DENY β€” prevents clickjacking
  • βœ… Content-Security-Policy: default-src 'none'; frame-ancestors 'none' β€” prevents XSS and framing
  • βœ… Cache-Control: no-store, no-cache, must-revalidate β€” prevents caching of sensitive data
  • βœ… Referrer-Policy: no-referrer β€” prevents referrer leakage
  • βœ… Permissions-Policy: camera=(), microphone=(), geolocation=() β€” restricts browser APIs
  • ⚠️ CORS wildcard warning β€” server logs a warning when CORS origin is *

Rate Limiting & Timeouts

  • βœ… Built-in Rate Limiting β€” 100 requests/minute per IP (sliding window with Retry-After header)
  • βœ… Health check exempt β€” /health endpoint bypasses rate limiting
  • βœ… Trust Proxy β€” opt-in --trust-proxy for X-Forwarded-For IP extraction behind reverse proxies
  • βœ… Server Timeouts β€” Request, keep-alive, and headers timeouts prevent slowloris-style DoS

Session Management (Stateful Mode)

  • βœ… UUID-based session IDs (cryptographically random)
  • βœ… Explicit session termination via DELETE /mcp
  • βœ… Cross-protocol guard β€” SSE session IDs rejected on /mcp and vice versa

Request Size Limits

  • βœ… Configurable body limit via --max-body-bytes (default: 1 MB) β€” prevents memory exhaustion DoS

πŸ”‘ Authentication

Simple Bearer Token

Lightweight authentication for development or single-tenant deployments:

db-mcp --transport http --auth-token my-secret --sqlite-native ./database.db
  • βœ… Clients must include Authorization: Bearer <token> on all requests
  • βœ… /health and / endpoints are exempt
  • βœ… Unauthenticated requests receive 401 with WWW-Authenticate: Bearer per RFC 6750

OAuth 2.1 (Enterprise)

Full OAuth 2.1 for production multi-tenant deployments:

  • βœ… RFC 9728 Protected Resource Metadata (/.well-known/oauth-protected-resource)
  • βœ… RFC 8414 Authorization Server Discovery with caching
  • βœ… JWT validation with JWKS support
  • βœ… Granular scopes: read, write, admin, db:{name}, table:{db}:{table}
  • βœ… Priority: When both --auth-token and --oauth-enabled are set, OAuth takes precedence
db-mcp --transport http --oauth-enabled \
  --oauth-issuer http://localhost:8080/realms/db-mcp \
  --oauth-audience db-mcp-server \
  --sqlite-native ./database.db

🐳 Docker Security

Non-Root User

  • βœ… Dedicated user: appuser (UID 1001) with minimal privileges
  • βœ… Restricted group: appgroup (GID 1001)
  • βœ… Restricted data directory: 700 permissions

Container Hardening

  • βœ… Minimal base image: node:24-alpine
  • βœ… Multi-stage build: Build dependencies not in production image
  • βœ… Production pruning: npm prune --omit=dev after build
  • βœ… Health check: Built-in HEALTHCHECK instruction
  • βœ… Process isolation from host system

Dependency Patching

The Dockerfile patches npm-bundled transitive dependencies for Docker Scout compliance:

  • βœ… diff@8.0.3 β€” GHSA-73rr-hh4g-fpgx
  • βœ… @isaacs/brace-expansion@5.0.1 β€” CVE-2026-25547
  • βœ… tar@7.5.11 β€” CVE-2026-23950, CVE-2026-24842, CVE-2026-26960
  • βœ… minimatch@10.2.4 β€” CVE-2026-26996
  • βœ… protobufjs/cli removed β€” CVE-2019-10790, CVE-2025-54798, CVE-2025-5889

Volume Mounting Security

# Secure volume mounting
docker run -v ./data:/app/data:rw,noexec,nosuid,nodev writenotenow/db-mcp:latest

Resource Limits

# Apply resource limits
docker run --memory=1g --cpus=1 writenotenow/db-mcp:latest

πŸ”„ CI/CD Security

  • βœ… CodeQL analysis β€” automated static analysis on push/PR
  • βœ… Docker Scout β€” container image vulnerability scanning (hard-fail on fixable critical/high)
  • βœ… npm audit β€” dependency vulnerability checking (audit-level: moderate)
  • βœ… Dependabot β€” automated dependency update PRs
  • βœ… E2E transport parity β€” Playwright suite validates HTTP/SSE security behavior

🚨 Security Best Practices

For Users

  1. Set a CORS origin when exposing the HTTP transport on a network
  2. Use authentication β€” configure --auth-token or --oauth-enabled for HTTP deployments
  3. Keep Node.js updated: Use Node.js 24+ (LTS)
  4. Secure host system: Ensure your host machine is secure
  5. Use tool filtering: Expose only the tools you need (--tool-filter)
  6. Limit network access: Don't expose the HTTP transport to untrusted networks
  7. Use resource limits: Apply Docker --memory and --cpus limits

For Developers

  1. Parameterized queries only β€” never interpolate user input into SQL strings
  2. Zod validation β€” all tool inputs validated via schemas at tool boundaries
  3. No secrets in code β€” use environment variables (.env files are gitignored)
  4. Typed error classes β€” descriptive messages with context; don't expose internals
  5. Regular updates: Keep Node.js and npm dependencies updated
  6. Security scanning: Regularly scan Docker images for vulnerabilities

πŸ“‹ Security Checklist

  • Parameterized SQL queries throughout
  • WHERE clause validation with 10 dangerous pattern detections
  • Identifier sanitization (table, column, index names)
  • FTS5 / LIKE pattern sanitization
  • Input validation via Zod schemas
  • Code Mode sandbox isolation (Worker + VM modes)
  • Code Mode execution timeout (30s hard limit)
  • HTTP body size limit (configurable, default 1 MB)
  • Configurable CORS with wildcard subdomain matching
  • Rate limiting (100 req/min per IP, sliding window)
  • DNS rebinding protection (MCP SDK middleware)
  • Security headers (CSP, X-Content-Type-Options, X-Frame-Options, Cache-Control, Referrer-Policy, Permissions-Policy)
  • HSTS (opt-in)
  • Server timeouts (request, keep-alive, headers)
  • Bearer token authentication (RFC 6750)
  • OAuth 2.1 with JWT/JWKS validation (RFC 9728, RFC 8414)
  • Granular scope enforcement (read, write, admin, db:*, table:*:*)
  • Non-root Docker user
  • Multi-stage Docker build with production pruning
  • Transitive dependency CVE patching in Dockerfile
  • CI/CD security pipeline (CodeQL, Docker Scout, npm audit)
  • Structured error responses (no internal details leaked)
  • Comprehensive security documentation

🚨 Reporting Security Issues

Version Supported
1.x.x βœ…
< 1.0 ❌

If you discover a security vulnerability:

  1. Do not open a public GitHub issue
  2. Email security concerns to: admin@adamic.tech
  3. Include detailed reproduction steps and potential impact
  4. Allow reasonable time for a fix before public disclosure

Response Timeline

  • Initial Response: Within 48 hours
  • Status Update: Within 7 days
  • Fix Timeline: Depends on severity

We appreciate responsible disclosure and will acknowledge your contribution in our release notes (unless you prefer to remain anonymous).

πŸ”„ Security Updates

  • Container updates: Rebuild Docker images when base images are updated
  • Dependency updates: Keep npm packages updated via npm audit and Dependabot
  • Database maintenance: Run ANALYZE and PRAGMA optimize regularly
  • Security patches: Apply host system security updates

The db-mcp SQLite MCP server is designed with security-first principles to protect your databases while maintaining excellent performance and full SQLite capability.

There aren’t any published security advisories