Api Key Exposure in Chi with Cockroachdb
Api Key Exposure in Chi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Chi is a lightweight HTTP library for the Crystal programming language, commonly used to build APIs. When Chi services interact with CockroachDB, a distributed SQL database, improper handling of database credentials can lead to API key exposure. This typically occurs when developers embed CockroachDB connection strings, including usernames and passwords, directly into Chi route handlers or configuration files that are committed to version control. Because Chi routes often serve as endpoints for external clients, any accidental logging or error disclosure can surface these credentials.
The risk is compounded when CockroachDB is accessible over the network without strict network policies. If a Chi application returns detailed database errors to clients, those messages can reveal connection parameters or API keys used to authenticate to CockroachDB. For example, a stack trace that includes a password in a connection string is effectively an exposed API key. Since middleBrick scans unauthenticated attack surfaces, it can detect such exposure by analyzing OpenAPI specs and runtime responses for sensitive strings that resemble credentials, and it flags these as data exposure findings mapped to frameworks like OWASP API Top 10 and PCI-DSS.
An insecure Chi route might look like this, embedding a CockroachDB password directly in the code:
require "chi"
require "pg" # hypothetical PostgreSQL-compatible driver for CockroachDB
router = Chi::Router.new do
get "/debug" do |env|
db_url = "postgresql://admin:SuperSecret123@cockroachdb-host:26257/mydb"
conn = PG.connect(db_url)
conn.exec("SELECT * FROM users").to_a
end
end
If this route is reachable without authentication, middleBrick can identify the hard-coded password as a potential API key or credential. The scanner does not assume intent; it reports the finding with severity guidance and remediation steps. In a Pro or Enterprise plan, continuous monitoring would detect regressions if such strings reappear in tracked endpoints. The LLM/AI Security checks do not apply here, as this scenario involves traditional credential exposure rather than prompt injection or model output risks.
Additionally, if the Chi application exposes an endpoint that returns raw database configuration for debugging, the response might include connection strings that contain API keys. middleBrick’s Data Exposure check would flag such endpoints, and the prioritized finding would include remediation guidance: move credentials to environment variables or a secrets manager, and ensure error responses are generic. This approach aligns with compliance mapping to SOC2 and HIPAA controls around credential protection.
Cockroachdb-Specific Remediation in Chi — concrete code fixes
To remediate API key exposure when using CockroachDB with Chi, move database credentials out of the application code and into secure runtime configurations. Use environment variables and a secrets management approach, and ensure error handling does not leak sensitive data.
Here is a secure Chi route that reads the CockroachDB connection string from an environment variable:
require "chi"
require "pg"
db_url = ENV["COCKROACH_URL"] || raise("Missing COCKROACH_URL environment variable")
router = Chi::Router.new do
get "/users" do |env|
conn = PG.connect(db_url)
result = conn.exec("SELECT id, name FROM users")
result.to_a.map { |row| { id: row["id"], name: row["name"] } }
end
get "/debug/health" do |env|
{ status: "ok" }
end
end
In this example, the connection string is externalized. For production CockroachDB deployments, use a secrets manager to inject the environment variable at runtime. The Chi application should also implement structured error handling to avoid exposing database details:
require "chi"
require "pg"
db_url = ENV["COCKROACH_URL"] || raise("Missing COCKROACH_URL environment variable")
router = Chi::Router.new do
get "/data" do |env|
begin
conn = PG.connect(db_url)
conn.exec("SELECT sensitive_field FROM records")
rescue ex : PG::Error
# Return a generic error to avoid leaking connection details
env.response.status_code = 500
{ error: "Internal server error" }.to_json
end
end
end
Additionally, restrict CockroachDB network access so that only the Chi application’s runtime can reach it, and avoid using the default root user. Create a dedicated database user with minimal required privileges. For example, in CockroachDB SQL:
-- Create a limited-privilege user for the Chi application
CREATE USER chi_app WITH PASSWORD 'strong-password-generated-by-secrets-manager';
GRANT SELECT, INSERT, UPDATE ON DATABASE mydb TO chi_app;
-- Revoke public access to prevent unauthenticated connections
REVOKE CONNECT ON DATABASE mydb FROM PUBLIC;
These steps reduce the likelihood of API key exposure and align with findings that middleBrick reports as high-severity data exposure. The Pro plan’s continuous monitoring can alert you if environment variables change or if new endpoints inadvertently include credentials. The GitHub Action can enforce that no hard-coded database strings appear in pull requests, and the MCP Server allows you to trigger scans directly from your IDE when modifying Chi routes.