CRITICAL api key exposurecockroachdb

Api Key Exposure in Cockroachdb

How API Key Exposure Manifests in CockroachDB

API key exposure in CockroachDB applications occurs when database credentials or API tokens are inadvertently disclosed through the application's unauthenticated attack surface. CockroachDB's architecture, which supports both PostgreSQL wire protocol and a built-in HTTP API (DB Console), creates specific exposure patterns.

CockroachDB-Specific Attack Patterns:

  • Hardcoded Connection Strings in Application Code: Developers often embed full connection strings including passwords in application source code. For example, a Go application might hardcode a CockroachDB connection string:
    db, err := sql.Open("postgres", "postgresql://root:ExposedPassword123@localhost:26257/defaultdb?sslmode=disable")
    If this code is committed to a public repository or the binary is reverse-engineered, the key is compromised.
  • Connection Strings in Environment Variables without Protection: While better than hardcoding, storing full connection strings (including passwords) in environment variables can still lead to exposure if those variables are logged. CockroachDB's cockroach start command or ccloud CLI might generate such strings that get copied into CI/CD logs or .env files that are accidentally committed.
  • DB Console HTTP Endpoint Exposure: The CockroachDB DB Console (typically on port 8080) uses HTTP Basic Auth by default. If an application proxies or references this console, the Authorization: Basic <base64(user:password)> header might be logged in proxy logs, error pages, or client-side code. An attacker scanning the application's external endpoints could discover this header in responses if misconfigured.
  • SQL API Errors Revealing Credentials: CockroachDB's SQL API (port 26257) may return detailed error messages when authentication fails. If an application does not properly handle these errors, the response body might include the attempted connection string or password fragments. For example, an error like password authentication failed for user "app_user" confirms a valid username, aiding brute-force attacks.
  • Cloud Deployment Misconfigurations: In CockroachDB Dedicated or Serverless clusters, connection strings often include cloud IAM tokens or API keys. If these strings are used in client-side JavaScript (e.g., a direct browser connection to a CockroachDB Serverless endpoint), the key is exposed to anyone inspecting the page source. This is a critical OWASP API Top 10: Broken Authentication (A2) scenario.

CockroachDB-Specific Detection

Detecting API key exposure in CockroachDB deployments requires scanning both the application's external endpoints and any publicly accessible CockroachDB services. middleBrick's black-box scanner tests the unauthenticated attack surface, identifying where credentials might be leaked.

How middleBrick Identifies Exposure:

  • Response Body Scanning: middleBrick analyzes all HTTP responses for patterns resembling CockroachDB connection strings, Base64-encoded credentials, or cloud provider tokens. It detects strings like cockroachdb://, postgresql://, or ccloud cluster commands in error messages, JSON responses, or HTML comments.
  • Header Inspection: The scanner checks for Authorization headers in responses (which should never be present in server-to-client communication) and examines Set-Cookie headers for session tokens that might be used as API keys.
  • OpenAPI/Swagger Analysis: If the API provides an OpenAPI spec, middleBrick resolves all $ref and looks for security schemes (e.g., apiKey in headers) that might reference CockroachDB credentials. It cross-references these with runtime findings to see if the key is actually exposed in practice.
  • CockroachDB-Specific Signatures: The scanner includes patterns for CockroachDB error codes (e.g., XX000 for internal errors) that might leak internal connection details, and recognizes typical ccloud CLI output formats that could appear in logs.

Using middleBrick to Scan:

From the terminal, use the CLI tool to scan any API endpoint that interacts with CockroachDB:

middlebrick scan https://your-api.example.com

The resulting report will flag any Data Exposure findings with a high severity if API keys or connection strings are detected. The Authentication category may also be affected if weak or default credentials are found. Each finding includes the exact location (URL, response snippet) and a severity score.

For continuous integration, the GitHub Action can be configured to fail a pull request if a scan detects a critical exposure:

name: API Security Scan
uses: middleBrick/github-action@v1
with:
  endpoint: ${{ secrets.API_ENDPOINT }}
  fail_on_score_above: 60

This prevents deployment if a new key exposure is introduced.

CockroachDB-Specific Remediation

Remediation focuses on eliminating hardcoded secrets, securing credential storage, and configuring CockroachDB's native security features. The goal is to ensure API keys never appear in client-side code, logs, or error messages.

1. Use Environment Variables or Secret Managers (Never Hardcode)

Replace any hardcoded connection string with dynamic loading from a secure source. For example, in a Go application using the lib/pq driver (compatible with CockroachDB):

Incorrect (Exposed):

// DO NOT DO THIS
import "database/sql"

func connect() {
    // Password is visible in source code
    connStr := "postgresql://app_user:Secr3tP@[email protected]:26257/appdb?sslmode=verify-full"
    db, _ := sql.Open("postgres", connStr)
    // ...
}

Correct (Secure):

import (
    "database/sql"
    "os"
    _ "github.com/lib/pq"
)

func connect() {
    // Load from environment variable set by secure secret manager
    connStr := os.Getenv("COCKROACHDB_CONNECTION_STRING")
    if connStr == "" {
        log.Fatal("COCKROACHDB_CONNECTION_STRING not set")
    }
    db, err := sql.Open("postgres", connStr)
    // ...
}

The environment variable should be injected at runtime by a secret manager (e.g., HashiCorp Vault, AWS Secrets Manager) or orchestration platform (Kubernetes Secrets), never stored in code or config files.

2. Use CockroachDB's IAM Integration for Cloud Deployments

For CockroachDB Dedicated clusters on AWS, GCP, or Azure, use short-lived IAM tokens instead of static passwords. The ccloud CLI generates these tokens dynamically. In your application, use the ccloud service token via environment variable:

# Set by CI/CD from a secure vault
export COCKROACHDB_CLUSTER_ID="my-cluster-id"
export COCKROACHDB_SERVICE_TOKEN="$(ccloud service-token create --cluster $COCKROACHDB_CLUSTER_ID --ttl 1h)"

# Connection string uses the token
connStr := fmt.Sprintf("postgresql://%s@%s:%s/%s?sslmode=verify-full",
    os.Getenv("COCKROACHDB_SERVICE_TOKEN"),
    "free-tier.gcp-us-central1.cockroachlabs.cloud",
    "26257",
    "appdb",
)

This token expires quickly, limiting exposure impact. Never commit the token; generate it in a secure CI step.

3. Secure the DB Console and SQL API Endpoints

Ensure the CockroachDB DB Console (port 8080) and SQL API (port 26257) are not publicly accessible without authentication. In cockroach start, enforce TLS and strong passwords:

cockroach start --certs-dir=certs --listen-addr=localhost:26257 --http-addr=localhost:8080 --cache=25% --max-sql-memory=25%

For cloud clusters, use security groups or VPC peering to restrict access to application servers only. The application should connect via internal network, never exposing the DB ports to the internet.

4. Implement Proper Error Handling

Never propagate raw CockroachDB errors to API clients. Wrap database errors in generic messages:

// BAD: Returns raw DB error
http.Error(w, err.Error(), http.StatusInternalServerError)

// GOOD: Generic message, log details server-side
log.Printf("DB error: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)

This prevents connection string details or schema information from leaking.

5. Rotate Credentials Regularly

Use CockroachDB's ALTER USER ... PASSWORD to rotate passwords periodically. For cloud clusters, rotate IAM tokens via ccloud service-token rotate. Automate rotation using a CI/CD pipeline and update the secret manager accordingly.

After remediation, re-scan with middleBrick to confirm the exposure is resolved. The Data Exposure finding should disappear, and the overall security score should improve.

Frequently Asked Questions

Can middleBrick detect API keys in CockroachDB connection strings within my application's HTML/JavaScript responses?
Yes. middleBrick's scanner analyzes all HTTP response bodies for patterns resembling connection strings (e.g., 'postgresql://', 'cockroachdb://') and Base64-encoded credentials. If your frontend inadvertently includes a connection string in a script tag or data attribute, it will be flagged as a critical Data Exposure finding.
Does scanning a CockroachDB Serverless endpoint with middleBrick require any database credentials?
No. middleBrick performs unauthenticated black-box scanning only. It does not require or use any database credentials. The scanner tests what an anonymous internet user can discover by probing your API's public endpoints, which is exactly how attackers operate.