Data Exposure in Axum with Cockroachdb
Data Exposure in Axum with Cockroachdb — how this specific combination creates or exposes the vulnerability
The Data Exposure check in middleBrick examines whether responses inadvertently return sensitive information such as database identifiers, internal schema details, or raw query results. When an Axum service connects to Cockroachdb, several patterns can increase the likelihood of data exposure in production APIs. Axum is a Rust web framework that encourages strong typing and explicit handler design, but developers may inadvertently serialize entire database records or include debug information in responses.
With Cockroachdb, a distributed SQL database compatible with PostgreSQL wire protocol, Axum applications often use the postgres crate or an ORM like SeaORM or sqlx. If query builders or row mappers are not carefully constrained, responses may include columns that should be omitted, such as internal primary keys, timestamps, or foreign identifiers. For example, returning a full users table row that contains password_hash, email, and internal_role without selective field projection can expose sensitive data through endpoints intended for public or limited-access use.
Cockroachdb-specific behaviors can amplify exposure risks. Cockroachdb supports advanced SQL features such as array types, JSONB columns, and multi-region configurations. If Axum handlers directly pass user-controlled input into dynamic SQL without strict validation, responses may include database metadata or error details that reveal schema structure. For instance, a malformed JSONB query or an improperly handled array parameter might trigger verbose Cockroachdb errors that include table names or index details, which are then surfaced to API consumers.
Network and driver-level issues can also contribute to data exposure. When using TLS with Cockroachdb in Axum, misconfigured certificate validation or fallback to non-encrypted connections may expose query payloads and result sets in transit. Additionally, connection pooling settings that retain sensitive rows in logs or diagnostic output can lead to inadvertent leakage through monitoring or error-tracking systems. The combination of Axum’s flexibility and Cockroachdb’s feature-rich SQL surface increases the attack area if input validation, output filtering, and transport security are not explicitly enforced.
middleBrick’s Data Exposure checks simulate unauthenticated requests to detect whether endpoints return credentials, PII, internal IDs, or debug traces. By analyzing API responses and correlating them with OpenAPI/Swagger specs and Cockroachdb schema definitions, the scanner identifies mismatches between intended data exposure and actual behavior. This helps teams detect cases where broad SELECT statements or missing field-level authorization in Axum handlers result in sensitive Cockroachdb data being returned to clients.
Cockroachdb-Specific Remediation in Axum — concrete code fixes
Remediation focuses on strict field selection, safe query construction, and secure transport. In Axum, define dedicated response structures that include only necessary fields, and avoid returning raw database rows.
// Safe Axum handler with selective projection
use axum::{routing::get, Router};
use serde::Serialize;
use sqlx::postgres::PgPoolOptions;
#[derive(Serialize)]
struct UserPublic {
id: i64,
username: String,
email: String,
}
async fn get_user(
user_id: axum::extract::Path,
pool: axum::extract::State<sqlx::PgPool>
) -> Result<axum::Json<UserPublic>, (axum::http::StatusCode, String)> {
let row = sqlx::query_as!(
UserPublic,
"SELECT id, username, email FROM users WHERE id = $1",
user_id.0
)
.fetch_optional(pool.as_ref())
.await
.map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
match row {
Some(user) => Ok(axum::Json(user)),
None => Err((axum::http::StatusCode::NOT_FOUND, "User not found".into())),
}
}
pub fn app() -> Router {
Router::new().route("/users/:id", get(get_user))
}
This pattern ensures that only intended columns are selected, reducing the risk of exposing password hashes or internal roles. Use sqlx::query_as! with explicit structs to enforce compile-time column mapping and avoid accidental inclusion of sensitive fields.
When working with JSONB or array columns in Cockroachdb, validate and sanitize inputs before constructing dynamic queries. Prefer parameterized queries over string interpolation to prevent injection-driven data leakage.
// Safe JSONB query with validation
use serde_json::Value;
use sqlx::postgres::types::Json;
async fn get_user_preferences(
user_id: axum::extract::Path<i64>,
pool: axum::extract::State<sqlx::PgPool>
) -> Result<axum::Json<Value>, (axum::http::StatusCode, String)> {
let preferences: Value = sqlx::query_scalar(
"SELECT preferences FROM user_prefs WHERE user_id = $1"
)
.bind(user_id.0)
.fetch_one(pool.as_ref())
.await
.map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
Ok(axum::Json(preferences))
}
Ensure TLS is properly configured by using the Cockroachdb connection string with sslmode=verify-full and providing root certificates. In Axum, manage the pool with secure defaults.
// Secure Cockroachdb connection in Axum
let pool = PgPoolOptions::new()
.connect("postgresql://user:password@host:26257/dbname?sslmode=verify-full&sslrootcert=./cockroach-ca.pem")
.await
.expect("Failed to create pool");
Finally, integrate middleBrick into your workflow using the CLI to validate that these changes reduce data exposure. Run middlebrick scan <your-api-url> to obtain a Data Exposure score and prioritized findings. Teams on the Pro plan can enable continuous monitoring to detect regressions after schema or handler changes, while the GitHub Action can fail builds if the score drops below the configured threshold.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |